使用GROUP BY(sql)时使用COUNT显示0

时间:2017-03-05 04:20:36

标签: sql sql-server database

表架构:

customers (customerID: integer, fName: string, lName: string)
orders (orderID: integer, itemID: integer, aID: integer, customerID: integer, date: date)
items (itemID: integer, description: string, price: integer)

SQL:

SELECT customers.customerID, COUNT(orders.customerID)
FROM customers INNER JOIN orders
    ON customers.customerID = orders.customerID
GROUP BY customers.customerID

我如何显示每位客户的订单数量结果?当我使用GROUP BY时,它会移除COUNT(orders.customerID)NULL的行。有没有办法显示0?

1 个答案:

答案 0 :(得分:3)

不是过滤掉它的GROUP BY。这是INNER JOIN

您正在寻找LEFT JOIN

select customers.customerID,
    COUNT(orders.customerID)
from customers
left join orders on customers.customerID = orders.customerID
group by customers.customerID