SQL Server replace NULL by the last value [duplicate]

独自空忆成欢 提交于 2020-08-10 18:56:12

问题


I want to find a way to replace NULL values by the last not NULL value. I have a table like :

Date        Cost
2017-01-01  18.6046511
2017-01-03  22.9787234
2017-01-03  NULL
2017-01-12  18.8584937
2017-01-16  19.1827852
2017-01-16  NULL
2017-01-19  NULL
2017-02-21  NULL
2017-03-04  24.0597622
2017-03-28  NULL
2017-04-17  33.5398414
2017-04-17  NULL

I want to replace NULL value by the last not NULL value so the result will be like:

Date        Cost
2017-01-01  18.6046511
2017-01-03  22.9787234
2017-01-03  22.9787234
2017-01-12  18.8584937
2017-01-16  19.1827852
2017-01-16  19.1827852
2017-01-19  19.1827852
2017-02-21  19.1827852
2017-03-04  24.0597622
2017-03-28  24.0597622
2017-04-17  33.5398414
2017-04-17  33.5398414

回答1:


You can try the following query by creating a Group Using Window Frame (GUWF). source link.

create table MyTable ([dtDate] date, Cost decimal(18, 6))
insert into MyTable values 
('2017-01-01',  18.6046511),
('2017-01-03',  22.9787234),
('2017-01-03',  NULL),
('2017-01-12',  18.8584937),
('2017-01-16',  19.1827852),
('2017-01-16',  NULL),
('2017-01-19',  NULL),
('2017-02-21',  NULL),
('2017-03-04',  24.0597622),
('2017-03-28',  NULL),
('2017-04-17',  33.5398414),
('2017-04-17',  NULL)

SELECT dtDate, Cost = MAX(Cost) OVER (PARTITION BY c)
FROM
(
    SELECT dtDate, Cost
        ,c = count(Cost) OVER (ORDER BY dtDate)
    FROM MyTable
) a
ORDER BY dtDate;

Live Demo




回答2:


If current value is null, then return first value where date is lower or equal to current date.

SELECT *, ISNULL(Value, (SELECT TOP 1 Value FROM SomeTable WHERE Date <= t.Date AND Value IS NOT NULL ORDER BY ID DESC))
FROM SomeTable t

This is not tested, just written from head.



来源:https://stackoverflow.com/questions/62788777/sql-server-replace-null-by-the-last-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!