1

我有一个名为客户的基本表:

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

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

PS,这是我在自己的时间练习的东西的示例表,为下学期的数据管理做准备。

4

5 回答 5

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
于 2012-11-09T10:40:00.947 回答
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;
于 2012-11-09T10:52:19.353 回答
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
于 2012-11-09T10:40:24.860 回答
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
于 2012-11-09T10:41:56.107 回答
-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
于 2012-11-09T10:39:37.287 回答