SQL子查询以查找重复项

时间:2012-02-11 01:18:00

标签: sql-server sql-server-2008

这个问题与我的一分钟前有关。我在一张桌子上寻找重复的记录。我正在寻找匹配的字段“符号”和“TradeDate”。我有一个表的唯一ID字段。我的逻辑是:返回记录的ID字段不是具有计数>的最小ID值。 1表示该符号和日期组合。这就是我所拥有的... sql server在我运行之前不会抱怨它,然后它说我的子查询返回了多个值:

SELECT Symbol , ID FROM tblDailyPricingAndVol 
     WHERE (SELECT Count(TradeDate) FROM tblDailyPricingAndVol AS T2 
          WHERE T2.Symbol = Symbol AND T2.TradeDate = TradeDate GROUP BY Symbol) > 1 
          AND ID <> (SELECT MIN(ID) FROM tblDailyPricingAndVol AS T3 
               WHERE T3.Symbol = Symbol AND T3.TradeDate = TradeDate
          GROUP BY Symbol)

1 个答案:

答案 0 :(得分:2)

;WITH x AS
(
  SELECT ID, TradeDate, Symbol, 
    rn = ROW_NUMBER() OVER (PARTITION BY TradeDate, Symbol ORDER BY ID)
    FROM dbo.tblDailyPricingAndVol
)
SELECT ID, TradeDate, Symbol, rn
FROM x WHERE rn > 1
ORDER BY TradeDate, Symbol;

如果您的下一个问题是“现在我想删除重复项”,请让我省去一些麻烦,因为这是一个简单的改变:

;WITH x AS
(
  SELECT ID, rn = ROW_NUMBER() OVER (PARTITION BY TradeDate, Symbol ORDER BY ID)
    FROM dbo.tblDailyPricingAndVol
)
DELETE x WHERE rn > 1;