如何为状态为closed的NULL日期行填充对应静态日期?
现有数据表
| ID | Status | datecol |
|---|---|---|
| 1 | closed | 2024-04-18 |
| 2 | closed | 2024-04-12 |
| 3 | closed | NULL |
| 4 | closed | NULL |
需求说明
- ID 3于2024/4/19以
closed状态传入且datecol为NULL,需将其datecol填充为传入日期2024-04-19 - ID 4在ID 3传入5天后以
closed状态传入且datecol为NULL,需将其datecol填充为2024-04-24
你的尝试方案问题分析
你尝试的SQL语句:
Case when status = "closed" and datecol is null then getdate() else datecol end as dateecol
核心问题是getdate()会取执行语句时的系统当前时间,无法匹配每条记录的实际传入日期,比如ID 3需要固定填充2024-04-19、ID 4需要填充2024-04-24,用getdate()无法精准满足需求。
正确解决办法
场景1:明确知道每条记录的传入日期
直接针对指定ID执行更新:
-- 更新ID 3的datecol UPDATE 你的表名 SET datecol = '2024-04-19' WHERE ID = 3 AND Status = 'closed' AND datecol IS NULL; -- 更新ID 4的datecol UPDATE 你的表名 SET datecol = '2024-04-24' WHERE ID = 4 AND Status = 'closed' AND datecol IS NULL;
场景2:ID 4的日期依赖ID 3的传入日期计算
通过关联查询自动计算并填充:
UPDATE t4 SET t4.datecol = DATEADD(day, 5, t3.datecol) FROM 你的表名 t4 JOIN 你的表名 t3 ON t3.ID = 3 WHERE t4.ID = 4 AND t4.Status = 'closed' AND t4.datecol IS NULL AND t3.Status = 'closed';
场景3:插入数据时直接处理
如果是在插入阶段填充,直接将传入日期赋值给datecol:
-- 插入ID 3时 INSERT INTO 你的表名(ID, Status, datecol) VALUES(3, 'closed', '2024-04-19'); -- 插入ID 4时,基于ID 3的日期计算填充 INSERT INTO 你的表名(ID, Status, datecol) SELECT 4, 'closed', DATEADD(day,5,datecol) FROM 你的表名 WHERE ID=3;
内容的提问来源于stack exchange,提问作者Kofisam
相关产品推荐
相关产品推荐

