有一个名为r_no的列,它是与日期列
关联的三个重复值r_no date values
1 09-Apr-2016 03:49:24
1 09-Apr-2016 03:49:30
1 09-Apr-2016 03:49:40
我希望输出为:
1 09-Apr-2016 03:49:40
删除具有最新日期值的重复值
答案 0 :(得分:1)
假设您正在使用Microsoft SQL Server
:
SELECT TOP 1 ID, DATE FROM #TEMP ORDER BY DATE DESC
删除&显示最新的:
;WITH TTT AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID)SR, DATE, ID FROM #TEMP
)
DELETE FROM TTT WHERE DATE NOT IN(SELECT MAX(DATE) FROM TTT)
SELECT * FROM #TEMP
说明: CTE将获取所有记录并为每个唯一条目应用行号。每个附加条目都将获得递增数字。
答案 1 :(得分:0)
您可以直接从CTE表达式delete dublicate data使用Row_Number()函数,如下所示
;with cte as (
select
r_no, [date values],
ROW_NUMBER() over (partition by r_no order by [date values] desc) as rn
from temptbl
)
delete from cte where rn > 1
答案 2 :(得分:0)
您可以使用OUTER APPLY
。
SELECT DISTINCT yt.r_no, oa.[date values]
FROM YourTable yt
OUTER APPLY (SELECT TOP 1 [date values]
FROM YourTable
WHERE r_no = yt.r_no
ORDER BY [date values] DESC) oa
您也可以使用嵌入式查询执行此操作。
SELECT DISTINCT *
FROM YourTable yt
WHERE [date values] = (SELECT MAX([date values]) FROM YourTable WHERE r_no = yt.r_no)