表:测试
Batch Year Value
----------------------
A 2014 11
A 2015 0
A 2016 22
A 2017 0
A 2018 13
B 2015 10
B 2016 0
B 2017 29
B 2018 0
C 2013 24
C 2014 0
D 2015 27
D 2016 0
此处分批假定没有2015年的数据,它应该取自2014年的数据,类似地,如果特定批次的特定年份没有可用的数据,则应将上一年的数据分配给该年份。
我试图只通过批处理A来放入case语句,但是问题是我的查询显示子查询返回多行。
SELECT BATCH, YEAR,
(CASE WHEN VALUE = 0 THEN
(SELECT A.VALUE FROM TEST A, TEST B WHERE A.YEAR = B.YEAR-1 AND A.VALUE <> '0') ELSE VALUE END)
FROM TEST;
必需的输出表:
测试
Batch Year Value
---------------------
A 2014 11
A 2015 11
A 2016 22
A 2017 22
A 2018 13
B 2015 10
B 2016 10
B 2017 29
B 2018 29
C 2013 24
C 2014 24
D 2015 27
D 2016 27
答案 0 :(得分:0)
我使用下面的查询来达到您的结果
CREATE TABLE TEST1(Batch VARCHAR(10), Year INT, Value INT)
INSERT INTO TEST1
VALUES('A', 2014,11),
('A', 2015,0 ),
('A', 2016,22),
('A', 2017,0 ),
('A', 2018,13),
('B', 2015,10),
('B', 2016,0 ),
('B', 2017,29),
('B', 2018,0 ),
('C', 2013,24),
('C', 2014,0 ),
('D', 2015,27),
('D', 2016,0 )
SELECT batch, year, CASE WHEN value = 0 then LAG(value) OVER(PARTITION BY batch ORDER BY year) ELSE value END AS value
FROM TEST1
ORDER BY batch, year