简体   繁体   English

如何计算两个类别的不同值?

[英]How to count distinct values over two categories?

I have a SQL query that shows me the clients and product for each purchase 我有一个SQL查询,向我显示每次购买的客户和产品

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. 我用count(DISTINCT product)count(DISTINCT client)count(*)GROUP BY (client)GROUP BY (product)尝试,但是没有得到有用的解决方案。 When I try it with SELECT DISTINCT [rest of the query], I get what I want but without the count column. 当我用SELECT DISTINCT [查询的其余部分]尝试时,我得到了想要的但没有count列。

You don't need to use DISTINCT. 您不需要使用DISTINCT。 A simple GROUP BY with COUNT will do the trick. 一个简单的GROUP BY COUNT即可解决问题。

Oto Shavadze suggested this query: Oto Shavadze建议此查询:

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. COUNT将为您提供每个组中的行数。

Try this query and you will get the output. 尝试此查询,您将获得输出。 Here test_data is the table name. 这里的test_data是表名。 Please replace it with your table_name. 请用您的table_name替换它。

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

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

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