Select lines that appear more than once.

   TableOne

      PersonId        PersonScore
         1                10
         1                20
         2                99
         2                40
         3                45

I need to get only those lines where PersonId appears more than once. Below is the result I want to achieve

     PersonId        PersonScore
         1                10
         1                20
         2                99
         2                40

I am using 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

The problem is removing extra lines. It creates the first instance of any PersonId. Can anyone suggest a solution please

+4
source share
3 answers

You want to use count(*)as a window function, not row_number():

select t.PersonId, t.PersonScore
from (select t.*, count(*) over (partition by PersonId) as cnt
      from TableOne t
     ) t
where cnt > 1;
+4
source
SELECT *
FROM TableOne t1
JOIN (SELECT PersonId
      FROM TableOne
      GROUP BY PersonId
      HAVING COUNT(*) > 1) t2
on t1.PersonId = t2.PersonId
+1
source

:

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

Source: https://habr.com/ru/post/1532496/


All Articles