TableOne
PersonId PersonScore
1 10
1 20
2 99
2 40
3 45
我只需要获取PersonId出现超过一次的那些行,例如以下是我想要实现的结果集
PersonId PersonScore
1 10
1 20
2 99
2 40
我正在使用cte
;WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY i.PersonId ORDER BY i.PersonId) AS [Num]
FROM TableOne i
)
SELECT *
FROM cte
WHERE cte.Num > 1
问题是它删除了额外的行。它是任何PersonId的第一个实例。任何人都可以建议解决方案
答案 0 :(得分:4)
您希望将count(*)
用作窗口函数,而不是row_number()
:
select t.PersonId, t.PersonScore
from (select t.*, count(*) over (partition by PersonId) as cnt
from TableOne t
) t
where cnt > 1;
答案 1 :(得分:1)
SELECT *
FROM TableOne t1
JOIN (SELECT PersonId
FROM TableOne
GROUP BY PersonId
HAVING COUNT(*) > 1) t2
on t1.PersonId = t2.PersonId
答案 2 :(得分:1)
您可以使用简单的相关子查询:
SELECT PersonId, PersonScore
FROM dbo.TableOne t1
WHERE (SELECT COUNT(*)
FROM dbo.TableOne t2
WHERE t1.PersonId = t2.PersonID) > 1