How do i write the following Query in laravel - sql

I have this Query which i am trying to execute
$other = $this->electricityConnections->select('category_id')
->from('building_category_settings')
->where('building_id', '=', 52)
->where('hide_from_electricity_widget', '=', 1)
->groupBy('category_id')
->orderBy('kwh_used', 'desc');
$electCategory = $this->electricityConnections
->addselect(('MIN(IF(category.description IS NOT NULL,
category.description, your_electricity_yesterday_category.cat_desc)
as cat_desc'),
('SUM(kwh_used) as kwh_used'), ('SUM(cost) as cost'),
'your_electricity_yesterday_category.category_id')
->leftJoin('category as category',
'your_electricity_yesterday_category.category_id', '=', 'category.id')
->where('your_electricity_yesterday_category.category_id', '=', 11)
->where('your_electricity_yesterday_category.building_id', '=', 52)
->whereNotIn('your_electricity_yesterday_category.category_id', $other)
->get();
dd($electCategory);
But i keep getting this error
"message": "SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '.cat_desc) as cat_desc, SUM(kwh_used) as kwh_used,
SUM(cost) as cost' at line 1 (SQL: select
MIN(IF(category.description IS NOT NULL, category.description, your_electricity_yesterday_category.cat_desc) as cat_desc,
SUM(kwh_used) as kwh_used, SUM(cost) as cost,
your_electricity_yesterday_category.category_id from
your_electricity_yesterday_category left join category as
category on your_electricity_yesterday_category.category_id =
category.id where
your_electricity_yesterday_category.category_id = 11 and
your_electricity_yesterday_category.building_id = 52 and
your_electricity_yesterday_category.category_id not in (select
category_id from building_category_settings where building_id =
52 and hide_from_electricity_widget = 1 group by category_id order
by kwh_used desc))",
When I do toSql() to the code above I get the following below
"select `MIN(IF(category`.`description IS NOT NULL, category`.`description, your_electricity_yesterday_category`.`cat_desc)` as `cat_desc`, `SUM(kwh_used)` as `kwh_used`, `SUM(cost)` as `cost`, `your_electricity_yesterday_category`.`category_id` from `your_electricity_yesterday_category` left join `category` as `category` on `your_electricity_yesterday_category`.`category_id` = `category`.`id` where `your_electricity_yesterday_category`.`category_id` = ? and `your_electricity_yesterday_category`.`building_id` = ? and `your_electricity_yesterday_category`.`category_id` not in (select `category_id` from `building_category_settings` where `building_id` = ? and `hide_from_electricity_widget` = ? group by `category_id` order by `kwh_used` desc)"
What am i doing wrong?

I think the main problem is the addSelect part. You're missing a closing ) for MIN. Try using DB::raw when the selected columns include sql functions.
addselect(
DB::raw('MIN(IF(category.description IS NOT NULL, category.description, your_electricity_yesterday_category.cat_desc)) as cat_desc'),
DB::raw('SUM(kwh_used) as kwh_used'),
DB::raw('SUM(cost) as cost'),
'your_electricity_yesterday_category.category_id'
)

you are missing parentheses from end of below line
MIN(IF(category.description IS NOT NULL, category.description, your_electricity_yesterday_category.cat_desc)) as cat_desc
you need to close bracket before as cat_desc, this seems to be syntax issue.

You Can Use selectRaw, check docs: https://laravel.com/docs/9.x/queries#selectraw
->selectRaw("
MIN(IF(category.description IS NOT NULL, category.description, your_electricity_yesterday_category.cat_desc)) as cat_desc),
SUM(kwh_used) as kwh_used,
SUM(cost) as cost),
your_electricity_yesterday_category.category_id
")

. is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. . with ``
Personally, I wouldn't bother; I'd just rename the column.

Related

MariaDB server version for the right syntax to use near 'GROUP BY

I build my project based on Laravel 9 and try to get count data by date group. I write using DB::raw to get sql query like this:
$rawActive = "
SELECT
SBC.SITE,
OPR.OPERATOR,
COUNT(*) TMO_COUNT,
DATE_FORMAT( TMO.TMO_DATE, '%m%Y' ) BULANTAHUN
FROM
TOP_TMO TMO
INNER JOIN SUBSCRIBER SBC ON TMO.SUBSCRIBER_ID = SBC.ID
INNER JOIN OPERATOR OPR ON SBC.SITE_ID = OPR.ID
WHERE
SBC.SITE_ID = ".$siteId."
GROUP BY
DATE_FORMAT(
TMO.TMO_DATE,
'%m%Y')
";
$queryAct = DB::select(DB::raw($rawActive));
the siteId is from form request.
I search for some solutions include edit 'strict' => false, in database.php , but still not find any solution.
I try to return $rawActive, and this is the result.
SELECT
SBC.SITE,
OPR.OPERATOR,
COUNT(*) TMO_COUNT,
DATE_FORMAT( TMO.TMO_DATE, '%m%Y' ) BULANTAHUN
FROM
TOP_TMO TMO
INNER JOIN SUBSCRIBER SBC ON TMO.SUBSCRIBER_ID = SBC.ID
INNER JOIN OPERATOR OPR ON SBC.SITE_ID = OPR.ID
WHERE
SBC.SITE_ID = 134
GROUP BY
DATE_FORMAT(
TMO.TMO_DATE,
'%m%Y')
As you can see, the siteId are seen well.
I also try this query on mysql, it's work fine.
Thanks for your help.
You need to adjust config\database.php as below:
'mysql' => [
...
....
'strict' => true,
'modes' => [
//'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
],
]
You can try this. You can enclose $siteId with single quote. '123' will work same like 123 and it will helps breaking query when there is no value assigned in $siteId. Instead try to use parameterized query that will prevent this issue and also is recommended solution for securing raw query.
$rawActive = "
SELECT
SBC.SITE,
OPR.OPERATOR,
COUNT(*) TMO_COUNT,
DATE_FORMAT( TMO.TMO_DATE, '%m%Y' ) BULANTAHUN
FROM
TOP_TMO TMO
INNER JOIN SUBSCRIBER SBC ON TMO.SUBSCRIBER_ID = SBC.ID
INNER JOIN OPERATOR OPR ON SBC.SITE_ID = OPR.ID
WHERE
SBC.SITE_ID = '".$siteId."'
GROUP BY
DATE_FORMAT(
TMO.TMO_DATE,
'%m%Y')
";
$queryAct = DB::select(DB::raw($rawActive));

What is the syntax problem here using this subquery inside where clause

SELECT p.pnum, p.pname
FROM professor p, class c
WHERE p.pnum = c.pnum AND c.cnum = CS245 AND (SELECT COUNT(*) FROM (SELECT MAX(m.grade), MAX(m.grade) - MIN(m.grade) AS diff
FROM mark m WHERE m.cnum = c.cnum AND m.term = c.term AND m.section = c.section AND diff <= 20)) = 3
Incorrect syntax near ')'. Expecting AS, FOR_PATH, ID, or QUOTED_ID.
Consider the following example:
SELECT COUNT(1)
FROM SYSCAT.TABLES T
WHERE
(
-- SELECT COUNT(1)
-- FROM
-- (
SELECT COUNT(1)
FROM SYSCAT.COLUMNS C
WHERE C.TABSCHEMA=T.TABSCHEMA AND C.TABNAME=T.TABNAME
-- )
) > 50;
The query above works as is. But the problem is, that if you uncomment the commented out lines, you get the following error message: "T.TABNAME" is an undefined name. and least in Db2 for Linux, Unix and Windows.
You can't push external to the sub-select column references too deeply.
So, your query is incorrect.
It's hard to correct it, until you provide the task description with data sample and the result expected.
I can see a potential syntax errors: It seems that CS245 refers to a value c.cnum may take and not a column name. If that is the case, it should be enclosed in single quotes.

Postgresql "subquery in FROM must have an alias" error

I'm doing a quick query using Postgresql 8.2 and I've done queries like this a thousand times before, but I can't figure out why I'm getting this error. I probably am missing something obvious, but it's saying my "subquery in FROM must have an alias". I do have an alias for my subquery "inner", and I can't figure out why else I would be getting the error.
SELECT "Branch", "Zip_5", "CountofStops", avg("EarlyTime") As
"Average_Arrival_Time"
FROM
(SELECT branch_id as "Branch", substring(stop_zip_postal_code, 1, 5) as
"Zip_5", count(stop_name) as "CountofStops", min(actual_arrival_time) as
"EarlyTime"
FROM distribution_stop_information
WHERE company_no = '001' AND route_date > '3/13/2017'
GROUP BY branch_id, stop_zip_postal_code)
inner
GROUP BY "Branch", "Zip_5"
ORDER BY Zip_5
********** Error **********
ERROR: subquery in FROM must have an alias
SQL state: 42601
Hint: For example, FROM (SELECT ...) [AS] foo.
inner is a reserved keyword. Use another name as alias.
inner . . . think "inner join". You need a better alias than that.
SELECT Branch, Zip_5, CountofStops, avg(EarlyTime) As Average_Arrival_Time
FROM (SELECT branch_id as Branch, left(stop_zip_postal_code, 5) as Zip_5,
count(stop_name) as CountofStops,
min(actual_arrival_time) as EarlyTime
FROM distribution_stop_information
WHERE company_no = '001' AND route_date > '2017-03-13'
GROUP BY branch_id, stop_zip_postal_code
) b
GROUP BY Branch, Zip_5
ORDER BY Zip_5;
Notes:
Don't wrap column names in double quotes unless needed. They are just superfluous.
Use standard formats for date constants.
LEFT() is a convenient shorthand for substring( . . ., 1, . . .)

SQl - An expression of non-boolean type specified in a context where a condition is expected, near ')'

Getting this error with the following query in SQL Server 2014.
SELECT
[Case]
,[Course]
,[Device]
,[IntegerValue]
,[Question]
,IFL.[QuestionSimplified]
,[Revision]
,[Script]
,[TextValue]
,[Timestamp]
,[Type]
,[Variable]
,[Wave]
FROM [dbo].[CosmosData] CD
Left Outer join [dbo].[ImportedFacilityList] IFL on CD.[Variable] = IFL.[Variablename]
where
CD.[Script] = 'CARD-F' and
(select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
When I run the above query I am getting the beloiw error,
Msg 4145, Level 15, State 1, Line 20
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
Any help please?
You have this in the where clause:
and (select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
SQL needs a boolean expression. This is usually formed by using = or a similar comparison operator. In your case, I think you just exant exists:
exists (select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = 2)
That said, you might want a correlation clause as well.
Note: I removed the single quotes from the integer value. Only use single quotes for string and date constants.
based on the assumption that you are using case as a key in this table, you can use the follwing to return all rows from cosmos data where your conditions are applied and the select in your where clause has a match using the criteria within it.
SELECT
[Case]
,[Course]
,[Device]
,[IntegerValue]
,[Question]
,IFL.[QuestionSimplified]
,[Revision]
,[Script]
,[TextValue]
,[Timestamp]
,[Type]
,[Variable]
,[Wave]
FROM [dbo].[CosmosData] CD
Left Outer join [dbo].[ImportedFacilityList] IFL on CD.[Variable] = IFL. [Variablename]
where CD.[Script] = 'CARD-F'
and Case
IN
(select Case from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
Hope that helps any

Bigquery - Substitute field if other field is blank

I've got this code here:
select DealID,ExternalReference,order_number, sales_rule
from flostream.orders
join mobileheads.surveys on flostream.orders.ExternalReference = mobileheads.surveys.order_number
//where DealID is null
What I want to happen is IF DealID (in flostream.orders) is null, replace it with sales_rule (in mobileheads.surveys)
Please let me know if this can be done with Bigquery or if you can think of some workaround?
Thanks!
Nik
You need
IFNULL(expr, null_default)
If expr is not null, returns expr, otherwise returns null_default.
You should read more about them in the manual.
Your query would look like:
SELECT IFNULL(DealID,sales_rule) as DealID,
ExternalReference,
order_number,
sales_rule
FROM flostream.orders
JOIN mobileheads.surveys ON flostream.orders.ExternalReference = mobileheads.surveys.order_number