Sql Server - Find duplicates and return all but the original record


Scenario:

List Duplicates from UserLog by User but excluding the original record.

User
IDName
1Terry
2Jerry
User Log
IDUser IDCreated Date
1101/21/2020
2101/20/2020
3101/19/2020
4201/18/2020
5201/17/2020

Query:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
DECLARE @BeginDate DATETIME = '2019-01-10'
DECLARE @EndDate DATETIME = GETDATE()

SELECT ul.*
FROM   UserLog ul
       JOIN (SELECT UserLogID,
                    ROW_NUMBER()
                      OVER (
                        Partition BY u.UserID
                        ORDER BY u.CreatedDate ASC) rowId
             FROM   (SELECT UserID
                     FROM   UserLog u
                     WHERE  u.CreatedDate <= GETDATE()
                     GROUP  BY UserID
                     HAVING COUNT(DISTINCT UserID) > 1)dups) u2
         ON ul.UserID = u2.UserID
WHERE  ul.CreatedDate BETWEEN @BeginDate AND @EndDate
       AND u2.rowId <> 1 

Output:

User IDDataCreated Date
1entry 301/21/2020
1entry 201/20/2020
2entry 201/18/2020

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...