计算并加入Where

时间:2013-10-03 02:07:45

标签: sql tsql sql-server-2008-r2

客户

CustomerID Name
4001       John Bob
4002       Joey Markle
4003       Johny Brown
4004       Jessie Black

订单

OrderID    Customer   Status
50001      4001       Paid
50002      4002       Paid
50003      4001       Paid
50004      4003       Paid
50005      4001       Paid
50006      4003       Paid
50007      4004       Unpaid

我尝试了这次加入

Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
inner join Orders o
on c.Customer = o.Customer
Where o.Status = 'Paid'
Group by c.Customer

但这是结果。

Customer  TotalOrders
4001      3
4002      1
4003      2

未包含未付款的客户。我将如何包括所有客户?

Customer  TotalOrders
4001      3
4002      1
4003      2
4004      0

3 个答案:

答案 0 :(得分:5)

使用左连接

Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
left join Orders o
on c.Customer = o.Customer
Group by c.Customer

答案 1 :(得分:3)

您必须使用更复杂的left join才能统计Paid个:

SELECT c.customerid, count(o.orderid) TotalOrders
FROM customer c
LEFT JOIN orders o
ON c.customerid = o.customer AND o.status = 'Paid'
GROUP BY c.customerid

输出:

| CUSTOMERID | TOTALORDERS |
|------------|-------------|
|       4001 |           3 |
|       4002 |           1 |
|       4003 |           2 |
|       4004 |           0 |

查看工作小提琴here

答案 2 :(得分:2)

Select c.CustomerId, COUNT(o.OrderID) as TotalOrders
from Customer c
left join Orders o on c.CustomerId = o.Customer and o.[Status] = 'Paid'
Group by c.CustomerId

尝试以上方法。