SQL修订历史记录-使用sql store_proc删除旧记录

时间:2019-07-02 09:59:52

标签: sql-server tsql greatest-n-per-group

需要提取created_date和last_updated_date的最大日期并删除旧记录-请帮助store_proc

表名称:销售

表记录:

Country         Region   Sales  Created_Date    Text    Last_updated_date
United Kingdom  London   99     05-05-18 12:30  ABC     NULL
United Kingdom  London   100    05-05-18 12:30  ABC     07-05-19 12:30
Canada          British  300    06-02-19 12:30  NULL    NULL
Canada          British  300    06-02-19 12:30  NULL    08-02-19 12:30
India           Chennai  499    10-02-19 12:30  XYZ     NULL
India           Chennai  600    11-02-19 12:30  XYZ     NULL
India           Chennai  900    12-02-19 12:30  XYZ     NULL
Australia       Victoria  60    21-02-19 12:30  ASD     22-02-19 12:30
Australia       Victoria  90    23-02-19 12:30  ASD     24-02-19 12:30

必选输出:

Country         Region   Sales  Created_Date    Text    Last_updated_date
United Kingdom  London   100    05-05-18 12:30  ABC     07-05-19 12:30
Canada          British  300    06-02-19 12:30  NULL    08-02-19 12:30
India           Chennai  900    12-02-19 12:30  XYZ     NULL
Australia       Victoria  90    23-02-19 12:30  ASD     24-02-19 12:30

I tried considering max date of two date columns, but unable to delete NULL records which are in date column

DELETE A1  from Sales A1
Join
(SELECT 
   Country, Region, Text, Sales,
   (SELECT MAX(RevisedDate)
      FROM (VALUES (created_date),(last_updated_date)) AS UpdateDate(RevisedDate)) 
   AS RevisedDate
FROM Sales) A2
on A1.[Country] = A2.[Country]
and A1.[Region] = A2.[Region]
and  A1.[Text] = A2.[Text]
and A1.[Sales] != A2.[Sales]
where A1.created_date < A2.RevisedDate

0 个答案:

没有答案