简体   繁体   English

SQL计数不适用于null

[英]SQL count doesn't work with null

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;

This is my sql code. 这是我的SQL代码。 The table with COUNT doesn't show the row with 0 value.. 具有COUNT的表不会显示具有0值的行。

Does this do what you want? 这是您想要的吗?

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;

This should show all customers in NY along with the number of orders they have, even if they have no orders. 这应该显示纽约的所有客户以及他们的订单数量,即使他们没有订单。 I am curious though: how could someone be in a table called customers if they have no orders? 不过我很好奇:如果没有订单,某人怎么会在一个叫customers的表中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM