Sql server 如何根据日期删除副本
我有一张桌子,里面有几个客户id的副本。我想保留prendate_next最接近当前日期的行,并删除其余重复的行。请帮我怎么做。我是新来的Sql server 如何根据日期删除副本,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我有一张桌子,里面有几个客户id的副本。我想保留prendate_next最接近当前日期的行,并删除其余重复的行。请帮我怎么做。我是新来的 cust_id prendate_next 1000105737 2014-11-30 00:00:00.000 1000105836 2014-11-20 00:00:00.000 1000143646 2014-11-10 00:00:00.000 1000143646 2015-03-09 00:00:00.000 1000179487
cust_id prendate_next
1000105737 2014-11-30 00:00:00.000
1000105836 2014-11-20 00:00:00.000
1000143646 2014-11-10 00:00:00.000
1000143646 2015-03-09 00:00:00.000
1000179487 2014-12-05 00:00:00.000
1000182253 2015-01-01 00:00:00.000
1000192740 2014-10-02 00:00:00.000
1000192740 2015-01-10 00:00:00.000
1000199419 2015-09-30 00:00:00.000
1000170578 2014-12-26 00:00:00.000
1000188890 2015-06-23 00:00:00.000
1000189075 2015-03-01 00:00:00.000
1000189075 2015-03-01 00:00:00.000
1000189144 2015-04-04 00:00:00.000
ABS(DATEDIFF(DAY,prendate\u next,GETDATE())
计算从今天开始的prendate\u next
天数。此表中是否有其他唯一id?重复:是,我有一个月
;WITH cte AS (
SELECT cust_id, prendate_next,
ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY ABS(DATEDIFF(DAY,prendate_next,GETDATE()))) AS RowNumber
FROM MyTable
)
DELETE MyTable
FROM MyTable
INNER JOIN cte ON MyTable.cust_id = cte.cust_id
AND MyTable.prendate_next = cte.prendate_next
WHERE cte.RowNumber != 1