我正在尝试解决SQL问题,但是遇到这个问题时,我遇到了麻烦。
问题是:给一个表Plays
包含3列id
,title
和writer
。
第二个表是reservation
,其中有4列:
id, play_id (same is as in play table), number_of_tickets, theater
现在的问题是要找到包含ID(从播放表),title(从播放表)和reserved_tickets(必须按降序)的列组成的表。
答案 0 :(得分:0)
我将对play
的查询和对reservation
的聚合查询进行联接:
SELECT id, title, reserved_tickets
FROM play p
JOIN (SELECT play_id, SUM(number_of_tickets) AS reserved_tickets
FROM reservations
GROUP BY play_id) r ON p.id = r.play_id
ORDER BY 2 DESC
答案 1 :(得分:0)
这通常用JOIN
和GROUP BY
来表达:
SELECT p.id, p.title, COUNT(*) as reserved_tickets
FROM play p JOIN
reservations r
ON p.id = r.play_id
GROUP BY p.id, p.title
ORDER BY COUNT(*) DESC