删除SQL Server中的重复项

时间:2012-08-21 22:41:28

标签: sql sql-server

  

可能重复:
  SQL - How can I remove duplicate rows?

我的表格结构如下:

create table MnA
(id         int PRIMARY KEY IDENTITY    not null,
symbol      nvarchar(4)                 not null,
direction   nvarchar(4)                 not null,
start_dt    nvarchar(5)                 not null,
end_dt      nvarchar(5)                 not null,
start_doy   int                         not null,
end_doy     int                         not null,
avg_price   int                         not null,
min_price   int                         not null,
max_price   int                         not null,
avg_percent int                         not null,
min_percent int                         not null,
max_percent int                         not null,
history     text                        not null,
percent_hit int                         not null,
aw_length   int                         not null,
diff        int                         not null,
date_change int                         not null)

我想删除有相似之处的行。

如果该行具有相同的symbol, direction, start_doydiff,那么我希望保留具有最高avg_percent的行。

我将如何做到这一点?

1 个答案:

答案 0 :(得分:4)

DELETE target 
FROM MnA target INNER JOIN MnA temp 
     ON (target.symbol = temp.symbol 
         AND target.direction = temp.symbol
         AND target.start_doy = temp.start_doy
         AND target.diff = temp.diff
         AND target.id != temp.id 
         AND temp.avg_percent > target.avg_percent);

DEMO (sqlfiddle)。