简体   繁体   中英

Query to calculate the number of different products sold to a certain customer

Say there is an SQL table

SHIPMENTS(ProductNumber, ClientNumber, Quantity)
(1,1,4)
(2,5,2)
(1,1,2)
(4,1,5)
(2,5,3)

In the example above we notice that client #1 has made three purchases (twice the same product). Hence, the answer should be 2 since we're looking for the number of DIFFERENT products purchased by that client.

Applying this query

SELECT count(*)
FROM SHIPMENTS
WHERE ClientNumber = 1;

Will understandably give 3 as a result. And I can't think of the solution as to how to calculate only for the different products.

SELECT count(DISTINCT ProductNumber)
FROM SHIPMENTS
WHERE ClientNumber = 1;

This should do the trick. Adding DISTINCT takes every unique value once: http://www.w3schools.com/sql/sql_distinct.asp

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