[英]Oracle: Sql to update row of the same table based on value from another row of the same table
I need a sql to update the price column to 999 for the item records which meet the following condition: 我需要一个SQL将满足以下条件的商品记录的价格列更新为999:
ID LOCATION ITEM PRICE 1 NULL 101 0 2 123 101 0 3 NULL 102 0 4 NULL 102 0 5 124 103 0 6 NULL 103 0
ID LOCATION ITEM PRICE 1 NULL 101 999 2 123 101 0 3 NULL 102 0 4 NULL 102 0 5 124 103 0 6 NULL 103 999
Use IN
(or EXISTS
) to check for the existence of a record with the item number where location is not null. 使用
IN
(或EXISTS
)检查项目编号不为null的记录是否存在。
update items
set price = 999
where location is null
and item_id in (select item_id from items where location is not null);
I have created a table. 我已经创建了一张桌子。 Please find the query below.
请在下面找到查询。 Just execute and check.
只需执行并检查。 You should get the desired result as per your ask.
您应该根据自己的要求获得理想的结果。
CREATE TABLE TABLE1(ID INT, LOCATION INT, ITEM INT, PRICE INT)
INSERT INTO TABLE1 VALUES
(1, NULL, 101, 0),
(2, 123 , 101, 0),
(3, NULL, 102, 0),
(4, NULL, 102, 0),
(5, 124 , 103, 0),
(6, NULL, 103, 0);
SELECT* FROM TABLE1;
WITH CTE AS
(
SELECT ITEM, COUNT(*) AS COUNTLOC FROM TABLE1 WHERE LOCATION IS NULL GROUP BY ITEM
)
UPDATE TABLE1
SET PRICE = 999 WHERE ITEM IN(SELECT ITEM FROM CTE WHERE COUNTLOC<2) AND LOCATION IS NULL;
update TABLE1 t1
INNER JOIN (select t12.item from TABLE1 t12 where t12.LOCATION is null
GROUP BY t12.ITEM
HAVING count(t12.ITEM)=1)aaa on aaa.item = t1.ITEM
set t1.PRICE = 999 where t1.LOCATION is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.