简体   繁体   中英

How to count distinct values over two categories?

I have a SQL query that shows me the clients and product for each purchase

client    | product
-----------------------
Lucy Lu   | Banana
Lucy Lu   | Banana
Lucy Lu   | Pineapple    
Mad Damon | Banana
Mad Damon | Apple
Mad Damon | Apple
Peter Fox | Banana
Peter Fox | Banana
Peter Fox | Banana
Peter Fox | Apple    
Peter Fox | Apple 

I want to distinct these query but the count of each product for each customer, so I can see for each customer how much of each product he bought:

client    | product   | count
----------------------------
Lucy Lu   | Banana    | 2
Lucy Lu   | Pineapple | 1
Mad Damon | Banana    | 1
Mad Damon | Apple     | 2
Peter Fox | Banana    | 3
Peter Fox | Apple     | 2

I tried it with count(DISTINCT product) , count(DISTINCT client) , count(*) and GROUP BY (client) or GROUP BY (product) , but didn't get a useful solution. When I try it with SELECT DISTINCT [rest of the query], I get what I want but without the count column.

You don't need to use DISTINCT. A simple GROUP BY with COUNT will do the trick.

Oto Shavadze suggested this query:

select client, product, count(*) 
from t 
group by client, product;

Here you make groups based on the distinct values of (client, product) pairs. The COUNT will give you the count of rows in each of these group.

Try this query and you will get the output. Here test_data is the table name. Please replace it with your table_name.

SELECT count(product) as count,client, product from test_data group by product,client

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