填补 SQL Server 中年份序列的空白

SQu*_*reL 5 sql sql-server datetime window-functions gaps-and-islands

我有一个带有列的表AgePeriodYear。列Age总是从0开始,并且不具有固定的最大值(I使用的“年龄” 0至30在该示例中,但范围也可以是0至100等),值PeriodYear只出现在以一定的某些行年龄。

然而,Age随着PeriodYear出现的值发生变化,因此解决方案应该是动态的。NULL用正确Period和填充值的最佳方法是什么Year

我正在使用 SQL Server。

Age Period  Year
-----------------
0   NULL    NULL
1   NULL    NULL
2   NULL    NULL
3   NULL    NULL
4   NULL    NULL
5   NULL    NULL
6   NULL    NULL
7   NULL    NULL
8   NULL    NULL
9   NULL    NULL
10  NULL    NULL
11  NULL    NULL
12  NULL    NULL
13  NULL    NULL
14  NULL    NULL
15  NULL    NULL
16  NULL    NULL
17  NULL    NULL
18  NULL    NULL
19  NULL    NULL
20  NULL    NULL
21  46      2065
22  NULL    NULL
23  NULL    NULL
24  NULL    NULL
25  NULL    NULL
26  51      2070
27  NULL    NULL
28  NULL    NULL
29  NULL    NULL
30  NULL    NULL
Run Code Online (Sandbox Code Playgroud)

结果应该是这样的,该号码PeriodYear应增加和/或从最后已知值降低为PeriodYear

Age Period  Year      
-----------------
0   25      2044
1   26      2045
2   27      2046
3   28      2047
4   29      2048
5   30      2049
6   31      2050
7   32      2051
8   33      2052
9   34      2053
10  35      2054
11  36      2055
12  37      2056
13  38      2057
14  39      2058
15  40      2059
16  41      2060
17  42      2061
18  43      2062
19  44      2063
20  45      2064
21  46      2065
22  47      2066
23  48      2067
24  49      2068
25  50      2069
26  51      2070
27  52      2071
28  53      2072
29  54      2073
30  55      2074
Run Code Online (Sandbox Code Playgroud)

这是我的问题的更新,因为我没有详细说明我的要求:解决方案应该能够处理Age,Period和 的不同组合Year。我的起点永远是一个已知的AgePeriodYear组合。但是,我的示例中的组合Age= 21、Period= 46 和Year= 2065(或 26|51|2070 作为第二个组合)不是静态的。处的值Age= 21可以是任何东西例如Period= 2和Year= 2021无论组合(AgePeriodYear),则溶液应在填充间隙和完成序列从已知值下来向上计数和PeriodYear。如果一个Period值序列变为负数NULL,如果可能,解决方案应返回值。

sca*_*dge 2

看来你的年龄和年份总是有相同的增量,所以

select age, isnull(period,age +25) Period,  isnull(year,age+44) year  
from yourtable 
Run Code Online (Sandbox Code Playgroud)

或标准函数合并(如戈登·利诺夫建议)

select age, coalesce(period,age +25) Period,  coalesce(year,age+44) year  
from yourtable 
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用“coalesce()”——它是标准函数。 (2认同)