简体   繁体   English

SQL查询提供一列中的不同值,以及第二列中的不同值的计数

[英]SQL query to give distinct values from one column, and a count of distinct values from a second column

Say I have a table like this: 说我有一张这样的桌子:

column1 | column2
---------------------
1       | a
1       | b
1       | c
2       | a
2       | b

I need an SQL query to show the distinct values from column 1, and a count of the related distinct values from column 2. The output would look like: 我需要一个SQL查询来显示第1列中的不同值,以及第2列中相关的不同值的计数。输出如下所示:

column1 | count
-------------------
1       | 3
2       | 2

You could do something like this: 您可以执行以下操作:

SELECT column1, count(column2)
FROM table
GROUP BY column1

You should do a COUNT(DISTINCT ...) with a GROUP BY : 您应该使用GROUP BY进行COUNT(DISTINCT ...)

Select    Column1,
          Count(Distinct Column2) As Count
From      Table
Group By  Column1

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

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