我正在使用SQL Server 2014,我想根据两列填写:日期和ID。 如果ID改变,那么我需要停止前一个前转
这是我的数据集:
Date Id Score
--------------------------------------------
201508 1 24
201509 1 NULL
201510 1 NULL
201511 1 25
201512 1 NULL
201601 1 30
201602 1 NULL
201508 2 NULL
201509 2 NULL
201508 3 10
201509 3 NULL
所以我想得到以下内容:
Date Id Score
--------------------------------------------
201508 1 24
201509 1 24
201510 1 24
201511 1 25
201512 1 25
201601 1 30
201602 1 30
201508 2 NULL
201509 2 NULL
201508 3 10
201509 3 10
我试过这样的事但没有成功
SELECT
a.*,
COALESCE(a.Score, b.Score) AS FILLED_IN_VALUE
FROM
data a
OUTER APPLY (
SELECT TOP 1 x.Score
FROM data x
WHERE
a.Score IS NULL
AND x.Score IS NOT NULL
AND x.ID < a.ID
AND x.Date < a.Date
ORDER BY a.ID ASC, a.Date ASC
) b
答案 0 :(得分:2)
使用运行总和将行分类到组中。然后获得每组的最高分数。
select date,id,max(score) over(partition by id,grp) as score
from (select date,id,score,
sum(case when score is not null then 1 else 0 end) over(partition by id order by date) as grp
from tbl
) t