简体   繁体   中英

is there a way to show 2nd column in the resultset when doing a count of the 1st column

Is there a way to show 2nd column when doing a count of the 1st column?

lets say you have:

ID . Name
1 .  John
2 .  John
3    Peter
4 .  Sue
5 .  Sue
6 .  Sue

I want the resul set to show the Name AND ID that has count > = 2, even though it repeats like below:

Name  ID  Count(*)
John .1   2
John  2 . 2
Sue . 4 . 3
Sue . 5 . 3
Sue . 6 . 3

I know you can do:

select Name, count(ID)
from A
group by Name
having count(id) >= 2

but this only shows you the Name, so when I try:

select Name, ID, count(*)
from A
group by Name, ID
having count(*) >=2

I get nothing back, since its counting it per each line, is there way to bring back the Name and doing the count of id for the Name? I am using Oracle

Thanks

You can use window functions:

select Name, count(*) over (partition by name) as cnt
from A;

If you want to filter, then you can use a subquery:

select a.*
from (select Name, count(*) over (partition by name) as cnt
      from A
     ) a
where cnt >= 2;

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