带有Count和SUM函数的SQL在2个表上提供帮助

时间:2012-11-09 10:35:51

标签: mysql sql count sum

我有一个名为customer的基本表:

CustId Name
AB1    George Arkin
AB2    Indiana James
AB3    Michael Anjelo

和另一张名为booking的表:

CustId FlightId Price
AB1    FL134    43.00 
AB1    FL122    21.00
AB1    FL134    49.00
AB1    FL122    48.00  
AB2    FL291    40.00  
AB2    FL291    29.00  
AB2    FL293    22.00  
AB2    FL862    56.00  
AB2    FL862    12.00  
AB2    FL293    99.00  
AB3    FL900    100.00  

现在我要做的就是加入两张桌子。然后,我想计算一个人预订的航班数量(显示所有人),我还希望每个人的总价格在它旁边加上他们支付的每个价格的总和。到目前为止,我想出了这个:

SELECT C.CustId, C.Name, COUNT(DISTINCT B.FlightId) AS "NumberOfTicketsPurchased"
,      SUM(DISTINCT B.Price) AS "TotalPrice"
FROM customer C, booking B

但我只得到一个结果,总价格和数量不准确。

P.S这是我在自己的时间练习下一学期准备数据管理的一个示例表。

5 个答案:

答案 0 :(得分:1)

您需要GROUP BY才能使用Count和SUM等聚合函数。 你试过这个吗?

SELECT C.CustId, C.CName, Count(B.FlightId) , SUM(B.Price)
FROM customer C
LEFT JOIN booking b ON b.CustId = a.CustId 
GROUP BY  C.CustId

编辑

SELECT C.CustId, C.CName, Count(B.FlightId) , SUM(B.Price) as 'price'
FROM customer C
INNER JOIN booking b ON b.CustId = a.CustId 
GROUP BY  C.CustId
HAVING price > 75

答案 1 :(得分:1)

又一个SQL Fiddle

SELECT C.CustId, C.Name,
       COUNT(B.FlightId) AS "NumberOfTicketsPurchased",
       coalesce(SUM(B.Price), 0) AS "TotalPrice"
FROM customer C
left join booking B on c.custid = b.custid
group by c.custid, c.name;

答案 2 :(得分:0)

SELECT C.CustId, C.Name, COUNT(B.FlightId) AS "NumberOfTicketsPurchased"
,SUM(B.Price) AS "TotalPrice"
FROM customer C join booking B
on c.CustId = b.CustId 
group by C.CustId, C.Name

答案 3 :(得分:0)

首先,SUM(DISTINCT B.Price)永远不是一个好主意。如果两个航班的价格相同,则只计算一次。

在你的情况下,你只做一个join,所以根本不需要distinct

select  c.CustId
,       c.Name
,       count(b.FlightId) AS "NumberOfTicketsPurchased"
,       sum(b.Price) AS "TotalPrice"
from    customer c
left join
        booking b
on      b.CustId = c.CustId
group by
        c.CustId
,       c.Name

答案 4 :(得分:-1)

尝试

SELECT C.CustId, C.Name 
,COUNT(DISTINCT B.FlightId) AS "NumberOfTicketsPurchased", 
SUM(DISTINCT B.Price) AS "TotalPrice" 
FROM customer C, booking B 
GROUP BY C.CustId