2

我有一个大表,其中有重复项:

  • number(首要的关键),
  • group(首要的关键),
  • Division(首要的关键),
  • dateChange.

例子:

1,2,3,20121015

1,2,3,20120101

1,2,3,20110101

2,2,2,20121010

2,2,2,20120101

结果应该是:

1,2,3,20121015

2,2,2,20121010

我已经尝试了很多组合,包括按主键分组和最小的“changeDate”,但似乎没有什么能完美地工作。

我想要这样的东西:

delete from table where (number,group.devision,changeDate) not in 
(select from table(number,group,devision,Max(changeDate)) 
group by (number,group.devision)

但我认为它不是有效的 MS-SQL 语法。

您的帮助将不胜感激!!

4

2 回答 2

4

删除number, group, Division组合中除最新行之外的所有行。

;WITH cte
     AS (SELECT ROW_NUMBER() OVER (PARTITION BY number, group, Division 
                                       ORDER BY dateChange DESC) RN
         FROM   YourTable)
DELETE FROM cte
WHERE  RN > 1
于 2012-10-15T15:31:31.790 回答
0

以下应该工作。

delete table from
table inner join (select 
number, group, division, changeDate, row_number() over 
(partition by number, group, division order by changeDate desc) as ranker
from table) Z
on table.number  = Z.number and table.group = Z.group and 
table.changeDate = Z.changeDate and Z.ranker != 1
于 2012-10-15T15:37:19.807 回答