如何将带计数的SQL表加入?

时间:2019-06-28 07:36:36

标签: sql postgresql join inner-join outer-join

我正在尝试解决SQL问题,但是遇到这个问题时,我遇到了麻烦。

问题是:给一个表Plays包含3列idtitlewriter。 第二个表是reservation,其中有4列:

id, play_id (same is as in play table), number_of_tickets, theater

现在的问题是要找到包含ID(从播放表),title(从播放表)和reserved_tickets(必须按降序)的列组成的表。

2 个答案:

答案 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)

这通常用JOINGROUP 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