[英]SQL - lag/delay by YearMonth integer
我有这张桌子:
| YearMonth | Client_ID |
| 202001 | A |
| 201903 | A |
| 201802 | A |
| 202001 | B |
| 202001 | B |
我正在寻找这个 output,其中YearMonth_1
是(YearMonth - 1)
, YearMonth_2
是(YearMonth - 2)
,依此类推:
| YearMonth | Client_ID | YearMonth_1 | YearMonth_2 | YearMonth_3 |
| 202001 | A | 201912 | 201911 | 201910 |
| 201903 | A | 201902 | 201901 | 201812 |
| 201802 | A | 201801 | 201712 | 201711 |
| 202001 | B | 201912 | 201911 | 201910 |
| 201912 | B | 201911 | 201910 | 201909 |
在我的真实数据集中,直到YearMonth_8
,我的解决方案是:
SELECT YearMonth, Client_ID, (YearMonth - 1) AS YearMonth_1,
(YearMonth - 2) AS YearMonth_2, (YearMonth - e) AS YearMonth_3
FROM TABLE1
当YearMonth = 202001
时, YearMonth_1
将为202000
。 我解决这个问题:
UPDATE TABLE1
SET YearMonth_1 = 201912
WHERE YearMonth_1 = 202000
这是一个简单快捷的解决方案。 但是当您在我的真实数据集中到达YearMonth_3
或YearMonth_8
时,当YearMonth = 20XX01
YearMonth_8
,我必须UPDATE
YearMonth_3 的 3 个值或YearMonth_3
的 8 个值,这非常耗时。 有没有更有效的方法?
我会将值转换为日期:
select t.*,
year(dateadd(month, -1, yyyymm)) * 100 + month(dateadd(month, -1, yyyymm)),
year(dateadd(month, -2, yyyymm)) * 100 + month(dateadd(month, -2, yyyymm)),
year(dateadd(month, -3, yyyymm)) * 100 + month(dateadd(month, -3, yyyymm))
from t cross apply
(values (convert(date, concat(yearmonth, '01')))) v(yyyymm)
您实际上应该将EOMONTH(date)
存储为date
而不是奇怪的int
。
但是你不需要存储前 8 个值,你可以动态查询它:
SELECT
ClientID,
YearMonth,
YearMonth_1 = LAG(YearMonth, 1) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_2 = LAG(YearMonth, 2) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_3 = LAG(YearMonth, 3) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_4 = LAG(YearMonth, 4) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_5 = LAG(YearMonth, 5) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_6 = LAG(YearMonth, 6) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_7 = LAG(YearMonth, 7) OVER (PARTITION BY ClientID ORDER BY YearMonth,
YearMonth_8 = LAG(YearMonth, 8) OVER (PARTITION BY ClientID ORDER BY YearMonth,
FROM t
最好在(ClientID, YearMonth)
上建立索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.