![](/img/trans.png)
[英]Use SQL To Filter Table Where I Need to Sum Multiple Rows Of A Column Based On Another Column
[英]I delete from a table where if one column is null i need to use another column
DELETE FROM HERAPERM.SCRUBLITST
WHERE
CASE
WHEN ODUDAT IS NOT NULL
THEN ODUDAT > to_char(current_date - 2 month, 'MM')
ELSE ODCDAT > to_char(current_date - 2 month, 'MM')
END
這是獲得所需結果的一種方法。 創建一個臨時表來保存要刪除的行的主鍵,然后在將它們全部收集后從表中刪除它們。
DECLARE @foundIDs TABLE ( ID INT )
INSERT INTO @foundIDs
SELECT ID FROM HERAPERM.SCRUBLITST
WHERE ODUDAT IS NULL
AND ODUDAT > to_char(current_date - 2 month, 'MM')
INSERT INTO @foundIDs
SELECT ID FROM HERAPERM.SCRUBLITST
WHERE ODUDAT IS NOT NULL
AND ODCDAT > to_char(current_date - 2 month, 'MM')
DELETE FROM HERAPERM.SCRUBLITST
WHERE ID IN (SELECT ID FROM @foundIDs)
在關於無法在 DB2 中聲明臨時表的評論之后,這里是另一種方法:
DELETE FROM HERAPERM.SCRUBLITST
WHERE ID IN (SELECT ID FROM HERAPERM.SCRUBLITST
WHERE ODUDAT IS NULL
AND ODUDAT > to_char(current_date - 2 month, 'MM'))
OR ID IN (SELECT ID FROM HERAPERM.SCRUBLITST
WHERE ODUDAT IS NOT NULL
AND ODCDAT > to_char(current_date - 2 month, 'MM'))
沒有相關子查詢和需要 ID 的更簡單的解決方案:
DELETE FROM HERAPERM.SCRUBLITST
WHERE COALESCE (ODUDAT, ODCDAT) > to_char(current_date - 2 month, 'MM');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.