简体   繁体   中英

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. The table with COUNT doesn't show the row with 0 value..

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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