SQL Server:生成范围内缺失年份的行(系统年份 + 9)

Wil*_*son 3 sql-server select sql-server-2019

我有一个 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
Run Code Online (Sandbox Code Playgroud)

数据库<>小提琴


我希望每年至少有一行在此范围内:system year + 9。换句话说,我想要从当前年份(当前为 2023 年)开始 10 年的行。

但是,我缺少某些年份的行: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
Run Code Online (Sandbox Code Playgroud)

在 SQL Server 2019 查询中,如何选择行并生成 10 年范围内的填充行?

编辑:我不想在查询或表中手动创建年份列表。我宁愿在查询中创建一个动态范围。

spa*_*dba 5

这应该做:

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_
Run Code Online (Sandbox Code Playgroud)

它是如何工作的:您有一个作为 CTE 动态生成的“日历”表,只有十行(从现在到 9 年)。该 CTE 已加入到年份列的数据中。