创建一个显示以前汇率的列
Creating a column that'll show previous rates
我正在创建一个将显示旧地址的列。每当更新地址时,旧地址将在新地址生效的前一天过期,并且新地址将添加具有相同帐号的新行(例如:旧地址将显示:从:10/01 /2020 To: 12/31/2021 and the new address From: 01/01/2022 To: 12-31-9999).我试图为 SQL 中的每个帐号并排显示新旧地址,但我得到的是零。
示例数据
AccountNumber
Address
ValidFrom
ValidTo
4895626
720 Main
10/01/2020
12/31/2021
9794651
158 4th St
09/29/2002
12/19/2020
4895626
5986 9th Ave
01/01/2022
12/31/9999
期望的结果
AccountNumber
Address
ValidFrom
ValidTo
PreviousAddress
4895626
720 Main
10/01/2020
12/31/2021
0
9794651
158 4th St
09/29/2002
12/19/2020
0
4895626
5986 9th Ave
01/01/2022
12/31/9999
720 Main
DECLARE @PreviousValidTo DATE;
SELECT @PreviousValidTo = DATEADD(DAY, -1, Z.ValidFrom)
FROM Address.NewAddress Z
SELECT Address, ValidFrom, ValidTo
CASE
WHEN @PreviousValidTo = C.ValidFrom
THEN C.Address
ELSE 0
END AS PreviousAddress
FROM Address.NewAddress C
也许你可以使用 lag
select *,
Lag(address,1,'0') over(partition by accountnumber order by validto) PreviousAddress
from address.NewAddress
我正在创建一个将显示旧地址的列。每当更新地址时,旧地址将在新地址生效的前一天过期,并且新地址将添加具有相同帐号的新行(例如:旧地址将显示:从:10/01 /2020 To: 12/31/2021 and the new address From: 01/01/2022 To: 12-31-9999).我试图为 SQL 中的每个帐号并排显示新旧地址,但我得到的是零。
示例数据
AccountNumber | Address | ValidFrom | ValidTo |
---|---|---|---|
4895626 | 720 Main | 10/01/2020 | 12/31/2021 |
9794651 | 158 4th St | 09/29/2002 | 12/19/2020 |
4895626 | 5986 9th Ave | 01/01/2022 | 12/31/9999 |
期望的结果
AccountNumber | Address | ValidFrom | ValidTo | PreviousAddress |
---|---|---|---|---|
4895626 | 720 Main | 10/01/2020 | 12/31/2021 | 0 |
9794651 | 158 4th St | 09/29/2002 | 12/19/2020 | 0 |
4895626 | 5986 9th Ave | 01/01/2022 | 12/31/9999 | 720 Main |
DECLARE @PreviousValidTo DATE;
SELECT @PreviousValidTo = DATEADD(DAY, -1, Z.ValidFrom)
FROM Address.NewAddress Z
SELECT Address, ValidFrom, ValidTo
CASE
WHEN @PreviousValidTo = C.ValidFrom
THEN C.Address
ELSE 0
END AS PreviousAddress
FROM Address.NewAddress C
也许你可以使用 lag
select *,
Lag(address,1,'0') over(partition by accountnumber order by validto) PreviousAddress
from address.NewAddress