使用min(),count(),having子句的组合使用聚集的sql

时间:2018-11-14 04:52:03

标签: sql count min having

尝试查找允许我按组对名进行计数的代码,然后返回计数最少的名称。

样本数据:-

PersonGroup   FirstName
------------------------
A             Bob
A             Mary
A             Bob
A             Bob
B             Michelle
B             Michelle
B             Greg
B             Greg
B             Michelle
C             Cindy
C             Michelle
C             Michelle
D             Rod
D             Rod
D             Rod
D             Rod
D             Rod
D             Mary
D             Mary
D             Mary
D             Mary
D             Mary
D             Mary

需要的输出:

PersonGroup   FirstName    Count
--------------------------------
    A         Mary           1
    B         Greg           2
    C         Cindy          1
    D         Rod            5

“名字”列的名称在组中最少出现

“计数”列中的“名称”计数每组出现次数最少

到目前为止,这是我的代码,但是每个名称都将返回,

select
    PersonType,
    FirstName,
    count (firstName) as mycount
from
    [Person].[Person]
group by 
    FirstName,
    [PersonType]
having 
    count(firstName) = (select min(a.cnt)
                        from 
                             (select count(firstname) as cnt 
                              from [Person].[Person] 
                              group by [FirstName]) as a)
order by 
    PersonType desc

2 个答案:

答案 0 :(得分:1)

您可以使用row_number()

select a.*
from (select PersonType,FirstName ,count (firstName) as mycount, 
             row_number() over (partition by PersonType order by count(*)) as rn
      from [Person].[Person]
     group by FirstName,[PersonType]
     ) a
where rn= 1; 

答案 1 :(得分:1)

使用窗口功能8

row_number()

demo link

enter image description here