我有一个包含特定月份值的表:
| 制造商 | 日期 | 因素 | ----------------------------------------- | 1 | 2013-01-01 | 1 | | 2 | 2013-01-01 | 0.8 | | 2 | 2013-02-01 | 1 | | 2 | 2013-12-01 | 1.55 | | 3 | 2013-01-01 | 1 | | 3 | 2013-04-01 | 1.3 | | 3 | 2013-05-01 | 1.2 | | 3 | 2013-06-01 | 1.1 | | 3 | 2013-07-01 | 1 | | 4 | 2013-01-01 | 0.9 | | 4 | 2013-02-01 | 1 | | 4 | 2013-12-01 | 1.8 | | 5 | 2013-01-01 | 1.4 | | 5 | 2013-02-01 | 1 | | 5 | 2013-10-01 | 1.3 | | 5 | 2013-11-01 | 1.2 | | 5 | 2013-12-01 | 1.5 |
我想做的是使用calendar
表格(已经定义)来旋转这些:
最后,级联NULL
列以使用先前的值。
到目前为止,我得到的是一个查询,它将用NULL
s 的最后一个值填充 s mfg = 3
。每个mfg
人在一年的第一天总是有一个价值。我的问题是;我如何以此为中心并扩展到所有人mfg
?
SELECT c.[date],
f.[factor],
Isnull(f.[factor], (SELECT TOP 1 factor
FROM factors
WHERE [date] < c.[date]
AND [factor] IS NOT NULL
AND mfg = 3
ORDER BY [date] DESC)) AS xFactor
FROM (SELECT [date]
FROM calendar
WHERE Datepart(yy, [date]) = 2013
AND Datepart(d, [date]) = 1) c
LEFT JOIN (SELECT [date],
[factor]
FROM factors
WHERE mfg = 3) f
ON f.[date] = c.[date]
结果
| 日期 | 因素 | XFACTOR | --------------------------------- | 2013-01-01 | 1 | 1 | | 2013-02-01 | (空) | 1 | | 2013-03-01 | (空) | 1 | | 2013-04-01 | 1.3 | 1.3 | | 2013-05-01 | 1.2 | 1.2 | | 2013-06-01 | 1.1 | 1.1 | | 2013-07-01 | 1 | 1 | | 2013-08-01 | (空) | 1 | | 2013-09-01 | (空) | 1 | | 2013-10-01 | (空) | 1 | | 2013-11-01 | (空) | 1 | | 2013-12-01 | (空) | 1 |