我有一个看起来像这样的表:
DATE COST ID TYPE UNITS_SOLD COST_DATE SALE_DATE
------ ------ ---- -------- ----------- --------- ---------
01/02/15 2000 1 GAME NULL 01/02/15 NULL
01/03/15 NULL 1 GAME 3 NULL 01/03/15
01/04/15 NULL 1 GAME 6 NULL 01/04/15
02/04/15 3000 2 BOOK NULL 02/04/15 NULL
02/05/15 NULL 2 BOOK 5 NULL 02/05/15
我想将cost_date列中的空值替换为给定ID和类型的最新非null cost_date。
理想情况下,生成的表格如下所示:
DATE COST ID TYPE UNITS_SOLD COST_DATE SALE_DATE
------ ------ ---- -------- ----------- --------- ---------
01/02/15 2000 1 GAME NULL 01/02/15 NULL
01/03/15 NULL 1 GAME 3 01/02/15 01/03/15
01/04/15 NULL 1 GAME 6 01/02/15 01/04/15
02/04/15 3000 2 BOOK NULL 02/04/15 NULL
02/05/15 NULL 2 BOOK 5 02/04/15 02/05/15
我目前正在尝试进行自我加入并自行合并cost_date。有什么想法吗?
答案 0 :(得分:0)
UPDATE YourTable Y1
SET COST_DATE = (SELECT COALESCE(MAX(COST_DATE), @YourDefaultDATE)
FROM YourTable Y2
WHERE Y2.DATE < Y1.DATE)
WHERE COST_DATE IS NULL
注意如果找不到上一个日期,您仍可以NULL
,因此您需要COALESCE
和default value
已修订:当你说重新开始时,我想要你UPDATE
SELECT (SELECT COALESCE(MAX(COST_DATE), @YourDefaultDATE)
FROM YourTable Y2
WHERE Y2.DATE < Y1.DATE) as COST_DATE
FROM YourTable Y1
WHERE COST_DATE IS NULL
答案 1 :(得分:0)
我会尝试这样的事情:
update table a
set COST_DATE = (
select max(COST_DATE) from table b
where b.COST_DATE is not null
and b.id = a.id
and b.type = a.type
and b.date <= a.date
)
where COST_DATE is null