如何以这种方式加入3个表

时间:2018-04-12 09:46:52

标签: sql

我有3张桌子:

Table 1

Table 2

Table 3

我想要一个显示Movies.title,SUM(Bookings.price)和COUNT(BookingId)的结果表。

我尝试了下面的代码,但不断收到错误:

  

专栏' Movies.Title'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

SELECT Movies.Title, SUM(Bookings.Price) ASnewPrice, COUNT(Bookings.BookingId) AS Quantity 
FROM ((Orders
INNER JOIN Bookings ON Orders.BookingId = Bookings.BookingId)
INNER JOIN Movies ON Movies.MovieId = Bookings.MovieId)
WHERE UserId = @UserId AND Completed = @Completed 
ORDER BY Bookings.BookingId

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

SELECT 
  Movies.Title, SUM(Bookings.Price) AS newPrice,COUNT(Bookings.BookingId) AS Quantity 
FROM Orders 
INNER JOIN Bookings ON (Orders.BookingId = Bookings.BookingId)
INNER JOIN Movies ON (Movies.MovieId = Bookings.MovieId)
WHERE UserId = @UserId AND Completed = @Completed 
GROUP BY Movies.Title
ORDER BY Bookings.BookingId