0

See script below to find duplicates in SQL Server DB. Is there a cleaner way?

select itemnum 
from matusetrans a
where exists (select null 
              from matusetrans b 
              where a.itemnum = b.itemnum 
                and a.actualdate = b.actualdate 
                and a.matusetransid != b.matusetransid 
                and (a.rotassetnum = b.rotassetnum 
                     or (a.rotassetnum is null and b.rotassetnum is null))    
                and a.quantity = b.quantity)
group by itemnum
Janis S.
  • 2,526
  • 22
  • 32
WRD299
  • 37
  • 11

3 Answers3

1

You could try:

SELECT itemnum
FROM matusetrans
GROUP BY [ColumnNames]
HAVING 
COUNT(*) > 1
Riaan van Zyl
  • 538
  • 8
  • 17
1

Assuming you want to find duplicate itemnum in table,Please use below query

SELECT itemnum
FROM matusetrans
GROUP BY [ItemNum]
HAVING COUNT(ItemNum) > 1

Using HAVING COUNT(*) > 1 may give you result as all are distinct if there are any Datetime columns like order datetime which generally varies per record.

Thanks, Sree

sree
  • 1,870
  • 1
  • 21
  • 36
0

Another possibility (but not neccessarily "cleaner") might be

WITH cte AS(
  SELECT columns, ROW_NUMBER() OVER (PARTITION BY columns ORDER by columns) AS RowIdx
    FROM matusetrans
    GROUP BY columns
)
SELECT *
  FROM cte
  WHERE RowIdx > 1
Tyron78
  • 4,117
  • 2
  • 17
  • 32