使用 exists in sql 查找重复项,有没有更简洁的方法?

Uisng exists in sql to find duplicates, is there a cleaner way?

请参阅下面的脚本以在 SQL 服务器数据库中查找重复项。有更清洁的方法吗?

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

你可以试试:

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

假设您想在 table 中查找重复的 itemnum,请使用以下查询

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

使用 HAVING COUNT(*) > 1 可能会给您带来结果,因为如果有任何 Datetime 列(例如通常因记录而异的订单日期时间),所有结果都是不同的。

谢谢, 斯里

另一种可能性(但不一定"cleaner")可能是

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