表中的数据是跨国数据。在2017-04-01我们有单位,然后下一个交易是在2017-04-05上用单位7进行的。
现在,我想将所有缺失的交易日期的单位列更新为最后一个交易日期。
喜欢:关于2017-04-02,2017-04-03,2017-04-04单位应为5我尝试在sql中使用merge语句,但是没有成功。我将不胜感激。
答案 0 :(得分:3)
请使用以下数据尝试以下更新声明。
DECLARE @tblTest AS Table
(
col1 INT,
tdate date,
units INT
)
INSERT INTO @tblTest values (12344,'2017-04-01',5)
INSERT INTO @tblTest values (12344,'2017-04-02',NULL)
INSERT INTO @tblTest values (12344,'2017-04-03',NULL)
INSERT INTO @tblTest values (12344,'2017-04-04',NULL)
INSERT INTO @tblTest values (12344,'2017-04-05',7)
INSERT INTO @tblTest values (12344,'2017-04-06',NULL)
INSERT INTO @tblTest values (12344,'2017-04-07',NULL)
INSERT INTO @tblTest values (12344,'2017-04-08',NULL)
INSERT INTO @tblTest values (12344,'2017-04-09',NULL)
DECLARE @i int=0;
UPDATE @tblTest SET @i=units=0+ISNULL(units,@i)
SELECT * FROM @tblTest
<强>输出:强>
答案 1 :(得分:2)
试试这个SQL:
UPDATE TEST
SET UNITS = (SELECT TOP 1 UNITS
FROM TEST t1
WHERE t1.TDATE < TEST.TDATE
AND t1.UNITS IS NOT NULL
ORDER BY TDATE DESC)
WHERE UNITS IS NULL
答案 2 :(得分:0)
这是我一直使用的快速简便的解决方案。有关simple-talk.com的更多信息。
DECLARE
@Units int;
UPDATE Test
SET
@Units = Units = CASE WHEN Units IS NULL THEN @Units ELSE Units END
答案 3 :(得分:0)
COALESCE
我们可以使用这个场景的功能
DECLARE @tblTest AS Table
(
col1 INT,
tdate date,
units INT
)
INSERT INTO @tblTest values (12344,'2017-04-01',5)
INSERT INTO @tblTest values (12344,'2017-04-02',NULL)
INSERT INTO @tblTest values (12344,'2017-04-03',NULL)
INSERT INTO @tblTest values (12344,'2017-04-04',NULL)
INSERT INTO @tblTest values (12344,'2017-04-05',7)
INSERT INTO @tblTest values (12344,'2017-04-06',NULL)
INSERT INTO @tblTest values (12344,'2017-04-07',NULL)
INSERT INTO @tblTest values (12344,'2017-04-08',NULL)
INSERT INTO @tblTest values (12344,'2017-04-09',NULL)
DECLARE @i int=0;
UPDATE @tblTest SET @i=units=0+COALESCE(units,@i)
SELECT * FROM @tblTest
输出
col1 tdate units
12344 2017-04-01 5
12344 2017-04-02 5
12344 2017-04-03 5
12344 2017-04-04 5
12344 2017-04-05 7
12344 2017-04-06 7
12344 2017-04-07 7
12344 2017-04-08 7
12344 2017-04-09 7