SQL获取具有多个出现次数的重复组列表

时间:2018-04-15 07:46:11

标签: sql sql-server

我坚持应该是一个简单的查询,但我似乎无法得到我想要的结果。

我有一个人员列表,其中包含以下属性ID,GroupNo,LastName。 可以将多个人分配到同一GroupNo,并且他们可以具有不同或相同的姓氏。我只对列有同一GroupNo的多个姓氏的人员列表感兴趣。我还需要知道每个GroupNo / LastName组合中出现的次数。

例如,

ID| GroupNo | LastName
1 | 003000 | MURAD
2 | 003000 | MURAD
3 | 003000 | MURAD
4 | 004020 | MAZZA
5 | 004020 | BOOTH
6 | 010930 | ZHANG
7 | 010930 | YAN
8 | 010930 | ZHANG

结果应为:

GroupNo | LastName | Occurences
004020 | MAZZA | 1
004020 | BOOTH | 1
010930 | ZHANG | 2
010930 | YAN | 1

我尝试使用OVER(Partition By ...)条款,但没有太多运气。

非常感谢任何帮助! 谢谢。

3 个答案:

答案 0 :(得分:0)

我用这种方式找到了你的结果

DECLARE @test AS TABLE(ID INT ,GroupNo VARCHAR(10),LastName VARCHAR(100))

INSERT INTO @test
(
ID,
GroupNo,
LastName
)
VALUES(1,'003000','MURAD'),(2,'003000','MURAD'),(3,'003000','MURAD'),(1,'004020','MAZZA'),(1,'004020','BOOTH')
,(1,'010930','ZHANG'),(1,'010930','YAN'),(1,'010930','ZHANG')

SELECT t2.GroupNo,t2.LastName,COUNT(*)AS cnt FROM(
SELECT res.GroupNo , COUNT(*) AS cnt1 FROM(
SELECT t.GroupNo,t.LastName,COUNT(*) AS cnt FROM @test AS t
GROUP BY t.GroupNo , t.LastName) res
GROUP BY res.GroupNo
HAVING COUNT(*) > 1) res2
INNER JOIN @test AS t2 ON t2.GroupNo = res2.GroupNo
GROUP BY t2.GroupNo,t2.LastName

答案 1 :(得分:0)

你可以只使用group by并且必须只获得有多行的那些:

SELECT GroupNo,LastName,COUNT(*) AS Occurences
FROM your_table
GROUP BY GroupNo,LastName
HAVING COUNT(*)>1

答案 2 :(得分:0)

这是一个使用窗口函数的方法:

select groupno, lastname, cnt
from (select groupno, lastname, count(*) as cnt,
             min(lastname) over (partition by groupno) as min_lastname,
             max(lastname) over (partition by groupno) as max_lastname
      from t
      group by groupno, lastname
     ) gl
where min_lastname <> max_lastname
order by groupno, lastname;

这是另一种短语的方式,没有窗口函数:

select groupno, lastname, count(*) as cnt
from t
where exists (select 1
              from t t2
              where t2.groupno = t.groupno and t2.lastname <> t.lastname
             )
group by groupno, lastname
order by groupno, lastname;