SQL Server查询以重复列的最新值

时间:2019-02-14 22:44:11

标签: sql sql-server tsql window-functions

我有UsersWeeks的组合。用户获得在给定一周内发生的分数。如果是null,我需要在给定的一周内重复上一次可用的得分。

我已经尝试了多种解决方案,包括LAST_VALUE

SELECT UserId, StartOfWeekDate, Score ,LAST_VALUE(Score) 
OVER (PARTITION BY UserId ORDER BY StartOfWeekDate ASC) AS LastValue
FROM [ScoresByUserOverWeek]

当前看起来像这样:

UserId  StartOfWeekDate overall LastValue

12534   12/17/2018      NULL    NULL

12534   12/24/2018      NULL    NULL

12534   12/31/2018      320     320

12534   1/7/2019        NULL    NULL

12534   1/14/2019       NULL    NULL

12534   1/21/2019       NULL    NULL

12534   1/28/2019       345     345

12534   2/4/2019        NULL    NULL

12534   2/11/2019       NULL    NULL

预期:

UserId  StartOfWeekDate overall LastValue

12534   12/17/2018      NULL    NULL

12534   12/24/2018      NULL    NULL

12534   12/31/2018      320     320

12534   1/7/2019        NULL    320

12534   1/14/2019       NULL    320

12534   1/21/2019       NULL    320

12534   1/28/2019       345     345

12534   2/4/2019        NULL    345

12534   2/11/2019       NULL    345

1 个答案:

答案 0 :(得分:2)

您可以将子查询与CASE WHEN子句配合使用来实现:

SELECT UserId, StartOfWeekDate, Score ,
CASE WHEN Score IS NOT NULL THEN Score ELSE 
(SELECT TOP 1 Score FROM ScoresByUserOverWeek T2 WHERE T1.UserID = T2.UserID AND T1.StartOfWeekDate > T2.StartOfWeekDate  AND T2.Score IS NOT NULL ORDER BY T2.StartOfWeekDate DESC) 
END AS LastValue
FROM ScoresByUserOverWeek T1

实验

--Create Table and Insert Values
CREATE TABLE #TEMP (UserId INT, StartOfWeekDate DATETIME, Score INT)

INSERT INTO #TEMP (UserId , StartOfWeekDate , Score )

VALUES( 12534 , '20181217' , NULL ),
( 12534, '20181224' , NULL ),
( 12534, '20181231' , 320 ),
( 12534, '20190107' , NULL ),
( 12534, '20190114' , NULL ),
( 12534, '20190121' , NULL ),
( 12534, '20190128' , 345 ),
( 12534, '20190204' , NULL ),
( 12534, '20190211' , NULL )



--Execute Query
SELECT UserId, StartOfWeekDate, Score ,
CASE WHEN Score IS NOT NULL THEN Score ELSE 
(SELECT TOP 1 Score FROM #TEMP T2 WHERE T1.UserID = T2.UserID AND T1.StartOfWeekDate > T2.StartOfWeekDate  AND T2.Score IS NOT NULL ORDER BY T2.StartOfWeekDate DESC) 
END AS LastValue
FROM #TEMP T1

结果

enter image description here