我有一个SQL Server 2019表,该表具有特定年份的行:
with data (year_, amount) as (
select 2024, 100 union all
select 2025, 200 union all
select 2025, 300 union all
select 2026, 400 union all
select 2027, 500 union all
select 2028, 600 union all
select 2028, 700 union all
select 2028, 800 union all
select 2029, 900 union all
select 2031, 100
)
select * from data
YEAR_ AMOUNT
---------- ----------
2024 100
2025 200
2025 300
2026 400
2027 500
2028 600
2028 700
2028 800
2029 900
2031 100我希望在这个范围内每年至少有一行:system year + 9。换句话说,我希望行持续10年,从当前年份(当前为2023年)开始。
然而,在某些年份,我遗漏了行: 2023、2030和2032。所以我想为那些缺失的年份生成填充行。填充行的amount为null。
看起来是这样的:
YEAR_ AMOUNT
---------- ----------
2023 --filler
2024 100
2025 200
2025 300
2026 400
2027 500
2028 600
2028 700
2028 800
2029 900
2030 --filler
2031 100
2032 --filler在Server 2019查询中,如何选择行并在10年范围内生成填充行?
编辑:我不希望手动创建查询或表中的年份列表。我宁愿在查询中创建一个动态范围。
发布于 2023-01-24 09:43:35
这应该可以做到:
with data (year_, amount) as (
select 2024, 100 union all
select 2025, 200 union all
select 2025, 300 union all
select 2026, 400 union all
select 2027, 500 union all
select 2028, 600 union all
select 2028, 700 union all
select 2028, 800 union all
select 2029, 900 union all
select 2031, 100
),
calendar AS (
SELECT YEAR(GETDATE()) + offset AS YEAR_
FROM (
VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)
) AS v(offset)
)
select *
from calendar AS c
LEFT JOIN data AS d
ON c.YEAR_ = d.year_它的工作原理:您有一个作为CTE动态生成的“日历”表,只有10行(从现在到+9年)。该CTE将加入到您的年份列的数据中。
https://dba.stackexchange.com/questions/322479
复制相似问题