SQL计数不适用于null

时间:2015-10-17 09:44:30

标签: sql

SELECT 
    customers.customerNumber, customers.customerName,
    customers.state, customers.city,
    COUNT(orders.customerNumber) AS OrdSum
FROM 
    customers 
INNER JOIN 
    orders ON customers.customerNumber = orders.customerNumber
WHERE 
    (customers.state <> 'NY') AND (customers.country = 'USA')
GROUP BY 
    customers.customerName
ORDER BY customers.customerNumber;

这是我的sql代码。具有COUNT的表不显示具有0值的行。

1 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

SELECT c.customerNumber, c.customerName, c.state, c.city,
       COUNT(o.customerNumber) AS OrdSum
FROM customers c LEFT JOIN 
     orders o
     ON c.customerNumber = o.customerNumber
WHERE c.state <> 'NY' AND c.country = 'USA'
GROUP BY c.customerNumber, c.customerName, c.state, c.city
ORDER BY c.customerNumber;

这应该显示纽约的所有客户以及他们拥有的订单数量,即使他们没有订单。我很好奇:如果他们没有订单,怎么会有人在customers的表中呢?