LARAVEL, ELOQUENT, SQL - groupBy 1 - mysql

When I run the below SQL manually I get my expected results. I am trying to write the same query in Laravel's Eloquent and I get an error:
SQLSTATE[42000]: Syntax error or access violation: 1056 Can't group on 'aggregate' (SQL: select count() as aggregate from daily_menu inner join meals on daily_menu.id = meals.daily_menu_id left join fruits on fruits.meal_id = meals.id where lodge_id = 1 group by 1)*
The original SQL Query that works:
SELECT
d.id,
SUM(IF(f.id IS NULL, 0, 1)) AS fruit_count
FROM daily_menu d
JOIN meals m
ON d.id = m.daily_menu_id
LEFT JOIN fruits f
ON m.id = f.meal_id
GROUP BY 1
My Laravel Eloquent Implementation:
$query = $query
->select("daily_menu.id", DB::raw("SUM(IF(fruits.id IS NULL, 0, 1)) AS fruit_count"))
->join("meals", "daily_menu.id", "=", "meals.daily_menu_id")
->leftJoin("fruits", "fruits.meal_id", "=", "meals.id")
->groupBy(DB::raw("1"));

$query = $query
->select("daily_menu.id", DB::raw("SUM(IF(fruits.id IS NULL, 0, 1)) AS fruit_count"))
->join("meals", "daily_menu.id", "=", "meals.daily_menu_id")
->leftJoin("fruits", "fruits.meal_id", "=", "meals.id")
->groupBy(DB::raw("daily_menu.id"));
I shouldn't have used 1 I should have used the proper column alias.
Related: Can't fix this: "Cannot group by an aggregate"

Related

Cannot retrieve column using eloquent

I have a query that extracts student marks, but I want to also extract the name and surname of the student but I get the error
SQLSTATE[42000]: Syntax error or access violation: 1055 'shunifu_db.users.name' isn't in GROUP BY (SQL: select name, marks.student_id,ROUND(AVG(mark)) as mark from grades inner join grades_students on grades_students.grade_id = grades.id inner join users on grades_students.student_id = users.id inner join marks on marks.student_id = grades_students.student_id where grades.stream_id = 5 and assessement_id = 1 group by marks.student_id)
here is my code
$result = DB::table('grades')
->join('grades_students', 'grades_students.grade_id', '=', 'grades.id')
->join('users','grades_students.student_id','=','users.id')
->join('marks','marks.student_id','=','grades_students.student_id')
->where('grades.stream_id', $request->stream_name)
->where('assessement_id',$request->assessement)
->select(DB::raw('marks.student_id,ROUND(AVG(mark)) as mark'))
->groupBy('marks.student_id')
->get()
May be it will work
$result = DB::table('grades')
->join('grades_students', 'grades_students.grade_id', '=', 'grades.id')
->join('users','grades_students.student_id','=','users.id')
->join('marks','marks.student_id','=','grades_students.student_id')
->where('grades.stream_id', $request->stream_name)
->where('assessement_id',$request->assessement)
->select(DB::raw('users.id,users.name,ROUND(AVG(mark)) as mark'))
->groupBy(['users.id', 'users.name'])
->get()
Here I'm using user table for grouping and also fetching name.

MySQL: Invalid use of group function updating two columns with update/select

I am trying to update two columns within a table from a select statment in MySQL 5.7.
The error I get is "invalid use of group function"
Stmt:
UPDATE
catalog mpc
JOIN
reviews mpr ON mpr.merchant_id = mpc.MERCHANT_ID and mpr.sku = mpc.ARTICLE_ID
SET
mpc.RATING = avg(mpr.rating),
mpc.RATINGS = count(mpr.rating)
WHERE
mpr.MERCHANT_ID = 1
AND mpr.sku = '133';
It looks about right to me, what could be the problem here?
You must aggregate first in reviews and then join to catalog:
UPDATE catalog mpc
INNER JOIN (
SELECT merchant_id, sku, AVG(rating) avg_rating, COUNT(rating) count_rating
FROM reviews
WHERE merchant_id = 1 AND sku = '133'
GROUP BY merchant_id, sku
) mpr ON mpr.merchant_id = mpc.MERCHANT_ID and mpr.sku = mpc.ARTICLE_ID
SET mpc.RATING = mpr.avg_rating,
mpc.RATINGS = mpr.count_rating

How to avoid "Cannot perform an aggregate function on an expression containing an aggregate or a subquery" error

I am running this query:
SELECT DISTINCT
SUM(CASE WHEN b.CODNAT IN (SELECT item
FROM fnMAS_Parametro_para_Lista('CON_SPED_FISCAL_CFOPS_BLOCO_C_FORA'))
THEN 0 EKSE ROUND(ISNULL(10, 0), 2)
END)
FROM
##tmpARPCO a
INNER JOIN
ARPCO_ITENS_TOTALIZADORES b ON (b.numped = a.numped
AND b.seqped = a.seqped
AND b.tipo = 'P')
INNER JOIN
ArEmpresa c ON (c.codempresa = a.codempresa)
INNER JOIN
ArNat d ON (d.codnat = b.codnat)
WHERE
1=1
AND a.ESPEC IN ('NFE', 'NF', 'NFCE', 'NFA', 'NFFA', 'NFSE')
AND a.MODNF IN ('01', '1B', '04', '55', '65')
AND a.datentr BETWEEN '20180401' AND '20180430'
GROUP BY
a.codcad, a.numnf, a.datentr, b.sittrib
but I get the following message:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
The function that you can see, only returns me a list of code string from a table. How to solve that problem?
Thanks a lot for your help and time
Alexandre

Sql sum inside an other sql select

I would like to SUM the foglalas_mennyiseg field in the foglalas table.
With the code below, i get this error: Notice: Undefined index: foglalt
What am i doing wrong?
$sql =
"
SELECT
rendeles.rendeles_id,
rendeles.rendeles_gyarto,
rendeles.rendeles_termek,
rendeles.rendeles_mennyiseg,
rendeles.rendeles_szam,
rendeles.rendeles_status,
rendeles.rendeles_created,
rendeles.rendeles_visszaig,
gyarto.gyarto_nev,
termek.termek_nev,
termek.termek_egyseg,
(SELECT SUM(foglalas.foglalas_mennyiseg) AS foglalt FROM foglalas
WHERE foglalas.foglalas_rendeles_id = rendeles.rendeles_id)
FROM rendeles
LEFT JOIN gyarto ON rendeles.rendeles_gyarto = gyarto.gyarto_id
LEFT JOIN termek ON rendeles.rendeles_termek = termek.termek_id
ORDER BY rendeles_id DESC LIMIT $actual, $row_per_page
";
You need your name after your subquery
....
( SELECT SUM(foglalas.foglalas_mennyiseg)
FROM foglalas
WHERE foglalas.foglalas_rendeles_id = rendeles.rendeles_id
) AS foglalt
....

Rails 3, Kaminari - Error with :joins when using paginate

I have a function for prices with 2 joins and it works fine and dandy when I use it to call for prices. But now when I added Kaminari to be able to paginate, it gave me a error and I wonder if I can customize the "count*" function in Kaminari or is it my function for calling the products that's wrong?
This is in my controller
#prices = Price.select("`prices`.*").joins(:retailer, :retailer => :profile).
where(['product_id=? AND size_id=?', params[:prod_id], params[:si_id]]).
group(:retailer_id).order("SUM((prices.price * #{params[:amount].to_i}) + profiles.shippingCost)").page(params[:page])
Error code:
Mysql2::Error: Column 'retailer_id' in field list is ambiguous: SELECT COUNT(*) AS count_all, retailer_id AS retailer_id FROM `prices` INNER JOIN `retailers` ON `retailers`.`id` = `prices`.`retailer_id` INNER JOIN `profiles` ON `profiles`.`retailer_id` = `retailers`.`id` WHERE (product_id='1' AND size_id='3') GROUP BY retailer_id,retailer_id ORDER BY SUM((prices.price * 1) + profiles.shippingCost)
When I call the products without Kaminari the MYSQL looks like this.
SELECT `prices`.* FROM `prices` INNER JOIN `retailers` ON `retailers`.`id` = `prices`.`retailer_id` INNER JOIN `profiles` ON `profiles`.`retailer_id` = `retailers`.`id` WHERE (product_id='1' AND size_id='3') GROUP BY retailer_id ORDER BY SUM((prices.price * 1) + profiles.shippingCost)
Thanks in advance!
If ambiguous error then try explicit syntax for retailer_id.
e.g. retailers.retailer_id ,
profiles.retailer_id ,
prices.retailer_id.
ray
:retailer is duplicated inside your join clause.
Please change your join params to
.joins(:retailer => :profile)