[英]Update value of one record with the value of another record in the same table
[英]How to update a record by checking a value in another record in same table
我有一張桌子:
ID DATE RANGE STATUS
--------------------------------------------
123 30-SEP-2019 000 C
123 30-SEP-2019 001 NULL
345 25-SEP-2019 000 C
345 30-SEP-2019 001 NULL
567 30-SEP-2019 000 C
567 30-SEP-2019 001 NULL
789 27-SEP-2019 000 C
789 30-SEP-2019 001 NULL
具有相同 ID(例如 123)的記錄被視為具有不同 RANGE 的相同記錄。 我需要將 001 RANGE 記錄的狀態更新為 Y,其中 000 RANGE 記錄的日期應為 2019 年 9 月 30 日。
前任。 更新查詢應該將 ID - '123' 和 RANGE - '001' 的記錄的狀態更新為'Y',因為對於 ID - '123' 和 RANGE - '000' 記錄的 DATE 是'30-SEP- 2019 年'。 它還應該使用 ID - 567 更新 001 RANGE 記錄的狀態。
它不應更新 ID 789 和 345 的 001 RANGE 的狀態,因為那些 000 RANGE 記錄的 DATE 不等於 30-SEP-2019。
我怎樣才能做到這一點?
想到一個帶有過濾的相關子查詢:
update t
set status = (select t2.status
from t t2
where t2.id = t.id and t2.range = '000'
)
where date = '2019-09-30' and range = '001';
或者,如果 Gordon 的回答是正確的,您可以使用JOIN
:
UPDATE T1
SET status = T2.Status
FROM YourTable T1
JOIN YourTable T2 ON t1.id = t2.id
WHERE T1.[date] = '20190930'
AND T1.range = '001'
AND T2.range = '000';
使用自加入進行更新:
update t
set status = 'Y'
from tablename t inner join tablename tt
on t.id = tt.id and t.date = tt.date and t.status is null and tt.status is not null
您可以在 WHERE 子句中專門為要更改的范圍添加條件,例如:
WHERE t.range = '001' and tt.range = '000'
請參閱演示。
結果:
ID | DATE | RANGE | STATUS
--: | :---------- | ----: | :-----
123 | 30-SEP-2019 | 0 | C
123 | 30-SEP-2019 | 1 | Y
345 | 25-SEP-2019 | 0 | C
345 | 30-SEP-2019 | 1 | null
567 | 30-SEP-2019 | 0 | C
567 | 30-SEP-2019 | 1 | Y
789 | 27-SEP-2019 | 0 | C
789 | 30-SEP-2019 | 1 | null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.