Oracle:Sql根据同一个表中另一行的值更新同一个表的行

时间:2017-06-09 05:53:10

标签: sql oracle

对于满足以下条件的商品记录,我需要一个sql将price列更新为999:

  1. 两条记录的ITEM位置不应为空。
  2. 将价格更新为999,其中2条记录之一的位置为空。
  3.  
    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
    

    OUTPUT TABLE SAMPLE

     
    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
    

3 个答案:

答案 0 :(得分:0)

使用IN(或EXISTS)检查是否存在包含位置不为空的项目编号的记录。

update items
set price = 999
where location is null
and item_id in (select item_id from items where location is not null);

答案 1 :(得分:0)

我创建了一个表。请在下面找到查询。只需执行并检查。你应该按照你的要求获得所需的结果。

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;

答案 2 :(得分:0)

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