2017-08-22 50 views
1

我有一個包含商品和價格的表格,其中價格可以根據位置標識符而不同。我想這樣做是採取價格項目123,並將其應用到項目456爲所有地點MS-SQL將特定商品的價格更新爲與同一表格中的另一特定商品相同

storeid itemid price 
1  123 '6.95' 
1  456 '0.00' 
2  123 '4.95' 
2  456 '0.00' 

期望得到的結果是讓數據看起來像這樣:

storeid itemid price 
1  123 '6.95' 
1  456 '6.95' 
2  123 '4.95' 
2  456 '4.95' 

的storeid和itemid是整數,價格是varchar 我想過將所有123數據移動到臨時表,然後遍歷while循環更新每個storeid的定價,但希望可能會有更多直接的方式。

任何建議將不勝感激!

回答

1

這裏有一個方法,使用窗函數:

with toupdate as (
     select ip.*, 
       max(case when itemid = 123 then price end) over (partition by storeid) as new_price 
     from itemprices ip 
    ) 
update toupdate 
    set price = new_price 
    where toupdate.itemid = 456; 

傳統的SQL方法是:

update itemprices 
    set price = (select ip2.price from itemprices ip2 where ip2.storeid = ip.storeid and ip2.itemid = 123) 
    where itemid = 456; 

或使用join

update ip 
    set price = ip123.price 
    from itemprices ip join 
     itemprices ip123 
     on ip.storeid = ip123.storeid and ip123.itemid = 123 
    where ip.itemid = 456; 
+0

謝謝!那就是我一直在尋找的! – BrianCon

0

一種方法是使用加入:

UPDATE t 
SET t.Price = t2.price 
FROM table t 
JOIN table t2 on t.storeid = t2.storeid 
       and t2.itemid = 123 
WHERE t.itemid = 456 
相關問題