简体   繁体   中英

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:

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 :

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

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