0

Customer

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

Orders

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

I tried this join

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

But here is the result.

Customer  TotalOrders
4001      3
4002      1
4003      2

The customer with unpaid is not included. How I will include all the customer ?

Customer  TotalOrders
4001      3
4002      1
4003      2
4004      0
4

3 回答 3

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
于 2013-10-03T02:09:16.183 回答
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 |

请参阅此处的工作小提琴。

于 2013-10-03T03:01:20.167 回答
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

试试上面的。

于 2013-10-03T02:10:04.207 回答