简体   繁体   中英

Select all rows from one table and the sum from the second table based on the third table

I have a problem with creating a query that will show me all rows from one table and the sum of rows from another table with the same id.

I've written a query that is not valid because it skips the rows that are empty.

SELECT g.name, sum(w.points), sum(w.points2) 
FROM groups g, works w, students s 
WHERE g.group_id=s.group_id AND w.student_id=s.student_id 
GROUP BY g.group_id;

I tried also LEFT JOIN , but my query have error:

SELECT g.name, s.name, sum(w.points) points
FROM groups g 
    LEFT JOIN students s 
    ON s.group_id=g.group_id
    LEFT JOIN works w
    ON w.student_id=s.student_id
GROUP BY g.group_id;

Here fiddle

If there is no point in the group, it does not show it at all, and I would like all groups to be displayed, even with the sum of 0.


Example tables 示例表
Expected result

预期结果

This works when I run it :

SELECT g.name, sum(w.points), sum(w.points2)
FROM groups g LEFT JOIN
     students s
     ON g.group_id = s.group_id LEFT JOIN
     works w
     ON w.student_id = s.student_id
GROUP BY g.group_id;

If you want zeroes, use COALESCE() :

SELECT g.name, COALESCE(sum(w.points), 0),
       COALESCE(sum(w.points2), 0)
FROM groups g LEFT JOIN
     students s
     ON g.group_id = s.group_id LEFT JOIN
     works w
     ON w.student_id = s.student_id
GROUP BY g.group_id;
select subtable.name, sum(subtable.points),sum(subtable.points2) from
      (select gr.name,wr.points,wr.points2 from students as st 
       inner join works as wr on st.student_id = wr.student_id
       inner join groups as gr on gr.group_id = st.group_id) subtable
       group by subtable.name;

this should also work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM