在SQL内连接查询中包含SUM

时间:2018-06-18 21:51:16

标签: sql sum inner-join

我有两张桌子,电影和预订。我试图弄清楚如何让我的查询只返回唯一的电影ID /标题,并将每个电影中多个条目的表中列出的票证总数相加。 以下是我尝试的,没有运气。我在这里缺少什么?

SELECT movies.id AS id, movies.title AS title, SUM(reservations.number_of_tickets) AS sold_tickets
FROM reservations
INNER JOIN movies ON reservations.movie_id = movies.id
ORDER BY sold_tickets DESC, id

当我在不尝试SUM的情况下运行查询时,我几乎得到了我想要的内容,除了查询对同一部电影有多行:

SELECT movies.id AS id, movies.title AS title, reservations.number_of_tickets AS sold_tickets
FROM reservations
INNER JOIN movies ON reservations.movie_id = movies.id
ORDER BY sold_tickets DESC, id

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您错过了GROUP BY

SELECT m.id, m.title, SUM(r.number_of_tickets) AS sold_tickets
FROM movies m INNER JOIN
     reservations r 
     ON r.movie_id = m.id
GROUP BY m.id, m.title
ORDER BY sold_tickets DESC, id;

注意:

  • 学习使用子查询。
  • 无需将列重命名为相同名称。因此movies.id已在结果集中调用id
  • 我换了join s的顺序。如果您想要无预约的电影,我可以将INNER JOIN变为LEFT JOIN