简体   繁体   中英

Select from multiple tables joined by column where condition is met

There are two tables,

table1:

name     | surname | firstname 

cookie   | Smith   | John     
cake     | Miller  | Ben    

table2:

name     | day | points1 | points2

cookie   | 1   | 5       | 5
cookie   | 1   | 4       | 6
cake     | 1   | 7       | 3
cake     | 1   | 7       | 3
cookie   | 2   | 4       | 4
cookie   | 2   | 4       | 4
cake     | 2   | 1       | 2    
cake     | 2   | 3       | 4    

We need the day and SUM(points1 + points2) AS total GROUP BY day, name as well as surname and firstname from table1, where the name from table1 and table2 match, if the total is larger than 15. Additionally the result should be ORDER BY total DESC, surname ASC.

The result should yield:

surname | firstname | day | total

Miller  | Ben       | 1   | 20
Smith   | John      | 1   | 20
Smith   | John      | 2   | 16

Ben Miller (cake) does not appear, since his total of day 2 is only 10.

Note that each name in table2 has an entry in table1.

Well, if you want " surname " and " firstname " to appear on your results, you will have to GROUP by these fields too (All SELECT fields in a GROUP BY expression must be an aggregation (SUM, AVG,...) or appear in the GROUP BY clause).

By using HAVING you can restrict the results of the GROUP BY.

I think this code would work:

SELECT surname, firstname, day, (SUM(points1) + SUM(points2)) AS total
FROM table1, table2
WHERE table1.name = table2.name
GROUP BY  surname, firstname, day
HAVING (SUM(points1) + SUM(points2) > 15
ORDER BY total DESC, surname ASC;

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