简体   繁体   中英

How to get distinct values in other columns per value in the primary column

I'm a beginner in oracle and I can't seem to do this I'm trying to do the following

From:

Col1 | Col2 |  Col3
--------------------
Mike | Tree | Acacia
Mike | Tree | Life
Mike | Tree | Seed
Mike | Plant| Seed
Mike | Tree | Seed

To:

Col1 | Col2 | Col3
------------------
Mike | 2    | 3

I could not seem to grasp how to do this.

I tried

SELECT Col1, COUNT(distinct Col2) , COUNT(distinct Col23)
from TABLE 
GROUP BY COL1,COL2,COL3

What shows up is

Col1 | Col2| Col3
-----------------
Mike | 1   | 1
Mike | 1   | 1
Mike | 1   | 1
Mike | 1   | 1
Mike | 1   | 1

The group by clause specifies which distinct values you'd like to keep (having the other select list items aggregate terms). Per distinct combination of col1, col2, col3 , there's of course only one different col2 or col3 , which explains why all your results are 1 . To make a long story short - only col1 should be in the group by clause:

SELECT   col1, COUNT(DISTINCT col2) , COUNT(DISTINCT col3)
FROM     mytable
GROUP BY col1

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