CustomerKey Person_Number Start_Date End_Date
1 250644 2017-01-01 4712-12-12
2 250644 2017-01-10 4712-12-12
3 250644 2017-01-15 4712-12-12
我需要SQL查询,其中下一个Start_Date-1和最后一个结束日期要更新的结束日期应为4712-12-12。
CustomerKey Person_Number Start_Date End_Date
1 250644 2017-01-01 2017-01-09
2 250644 2017-01-10 2017-01-14
3 250644 2017-01-15 4712-12-12
答案 0 :(得分:1)
一种方法是使用lag()
。这需要在update
中进行自我联接:
update t
set end_date = next_start_date - interval '1 day'
from (select t.*,
lead(start_date) over (partition by person_number order by start_date) as next_start_date
from t
) tt
where tt.customerkey = t.customerkey and
tt.next_start_date is not null;
尽管以上基本上适用于SQL Server(日期算术除外),但该问题最初被标记为Postgres。更好的SQL Server解决方案是:
update tt
set end_date = dateadd(day, -1, next_start_date)
from (select t.*,
lead(start_date) over (partition by person_number order by start_date) as next_start_date
from t
) tt
where tt.next_start_date is not null;
在SQL Server中不需要自联接。
答案 1 :(得分:0)
根据当前值更新上一行:
update t1
set t1.End_Date = dateadd(day, -1, t2.Start_Date)
from tbl t1
inner join tbl t2 on t1.CustomerKey = (t2.CustomerKey - 1)