Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL how to calculate average with grouping of rows

Suppose I have this table:

Name Marks Subject
A 10 Maths
B 8 English
A 6 English
B 8 Maths
C 2 Chemistry

Now I want to find, for which names is average Maths score greater than average English score?

I have tried running this query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT name FROM "xyz_table" 
GROUP BY name
HAVING (SELECT avg(marks) FROM "xyz_table" where Subject = 'Maths' GROUP BY subject) < (SELECT avg(conv_price(price)) FROM "xyz_table" where subject = 'English' GROUP BY subject)

Can you please help, I am a newbie to SQL and am stuck on this query.
Thank you for your response.

>Solution :

SELECT Name
FROM your_table_name
GROUP BY Name
HAVING AVG(CASE WHEN Subject = 'Maths' THEN Marks ELSE 0 END) >
       AVG(CASE WHEN Subject = 'English' THEN Marks ELSE 0 END);

SELECT Name: We select the "Name" column to get the names of the students.

FROM your_table_name: Replace your_table_name with the actual name of your table.

GROUP BY Name: We group the rows by the "Name" column to calculate averages for each student separately.

HAVING AVG(CASE WHEN Subject = ‘Maths’ THEN Marks ELSE 0 END) > AVG(CASE WHEN Subject = ‘English’ THEN Marks ELSE 0 END):

This part does the comparison. It calculate the average marks for "Maths" and "English" separately using conditional aggregation. If the average Maths score is greater than the average English score for a student, their name will be included in the result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading