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
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.