我想从下面的示例表中清除行,以便每个报告的三个最新版本(按名称)保留在表中。
ReportID是唯一标识符。每个名称的CreateDate按照降序对样本中的记录进行排序。
这可以在T-SQL查询中完成,还是我需要设置游标并以某种方式遍历表格?
CREATE TABLE #Reports (
[ReportID] int
, [Name] varchar(50)
, [CreateDate] datetime);
INSERT INTO #Reports (ReportID, [Name], CreateDate)
VALUES (3255, '2018 FTR RE Budget Acceptance Report', '2017-12-28 22:33:28.587'),
(3243, '2018 FTR RE Budget Acceptance Report', '2017-12-26 01:24:34.183'),
(3203, '2018 FTR RE Budget Acceptance Report', '2017-12-19 13:47:48.580'),
(3156, '2018 FTR RE Budget Acceptance Report', '2017-12-13 16:54:01.317'),
(3147, '2018 FTR RE Budget Acceptance Report', '2017-12-13 13:35:02.627'),
(3141, '2018 FTR RE Budget Acceptance Report', '2017-12-04 13:57:41.427'),
(3248, 'Audit Income Statement', '2017-12-26 22:53:50.067'),
(3246, 'Audit Income Statement', '2017-12-26 17:42:39.227'),
(3244, 'Audit Income Statement', '2017-12-26 17:25:18.477'),
(3099, 'Audit Income Statement', '2017-11-24 15:33:10.333'),
(3091, 'Audit Income Statement', '2017-11-24 14:59:16.283'),
(3252, 'FTR ND Budget Acceptance Report', '2017-12-28 22:33:28.260'),
(3240, 'FTR ND Budget Acceptance Report', '2017-12-26 01:24:33.837'),
(3200, 'FTR ND Budget Acceptance Report', '2017-12-19 13:47:48.267'),
(3153, 'FTR ND Budget Acceptance Report', '2017-12-13 16:54:01.067');
谢谢!
答案 0 :(得分:2)
这将保留最后3个版本(已更正以保留最后3个)
示例强>
;with cte as (
Select *,RN=Row_Number() over (Partition By Name ORder by CreateDate desc ) from #Reports
)
Delete from cte
Where RN>3
Select * from #Reports
更新了表格
ReportID Name CreateDate
3255 2018 FTR RE Budget Acceptance Report 2017-12-28 22:33:28.587
3243 2018 FTR RE Budget Acceptance Report 2017-12-26 01:24:34.183
3203 2018 FTR RE Budget Acceptance Report 2017-12-19 13:47:48.580
3248 Audit Income Statement 2017-12-26 22:53:50.067
3246 Audit Income Statement 2017-12-26 17:42:39.227
3244 Audit Income Statement 2017-12-26 17:25:18.477
3252 FTR ND Budget Acceptance Report 2017-12-28 22:33:28.260
3240 FTR ND Budget Acceptance Report 2017-12-26 01:24:33.837
3200 FTR ND Budget Acceptance Report 2017-12-19 13:47:48.267