繁体   English   中英

选择出现多次的行

[英]Select Rows that appear more than once

   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的第一个实例。 任何人都可以提出解决方案

您想使用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;
SELECT *
FROM TableOne t1
JOIN (SELECT PersonId
      FROM TableOne
      GROUP BY PersonId
      HAVING COUNT(*) > 1) t2
on t1.PersonId = t2.PersonId

您可以使用简单的相关子查询:

SELECT PersonId, PersonScore
FROM dbo.TableOne t1
WHERE (SELECT COUNT(*) 
       FROM dbo.TableOne t2 
       WHERE t1.PersonId = t2.PersonID) > 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM