[英]How to update values from one where condition to other where condition on same table and column using SQL
我想在不同的 where 條件下更新列值。 下面是例子
ID, Product, MonthID, Rate
1 , a, 201610, 13
2 , a, 201611, 22
3 , b, 201610, 29
4 , b, 201611, 14
SELECT rate
FROM dbo.sales
WHERE monthid = 201610
ID, Product, MonthID, Rate
1, a, 201610, 13
3, b, 201610, 29
我得到上面的費率值。 現在我想在不同的monthid
條件下在同一個表中看到這些費率列值,如下所示
SELECT rate
FROM dbo.sales
WHERE monthid = 201611
更新后結果:
ID, Product, MonthID, Rate
2, a, 201611, 13
4, b, 201611, 29
決賽桌:
ID, Product, MonthID, Rate
1, a, 201610, 13
2, a, 201611, 13
3, b, 201610, 29
4, b, 201611, 29
是否可以將速率值從一個 where 條件更新到另一個 where 條件?
update s
set rate = (select rate from dbo.sale where idmonth = 201610 and product = a.product )
from dbo.sales s
where idmonth = 201611
僅當您每個月只為每個產品記錄一次時才有效。
這可能有助於更新速率值。
update s1
set s1.rate = s2.rate
from sales s2 (nolock)
inner join sales s1
on s1.MonthID = s2.MonthID + 1 and s1.Product = s2.Product
where s2.MonthID = 201610
創建 V1(在 sql 中查看):SELECT id, Product, MonthID, Rate FROM dbo.tb1 WHERE (MonthID = 201610)
創建 V2(在 sql 中查看):SELECT id, Product, MonthID, Rate FROM dbo.tb1 WHERE (MonthID = 201611)
創建V3(在sql中查看):SELECT dbo.V1.id, dbo.V1.Product, dbo.V1.MonthID, dbo.V1.Rate, dbo.V2.id AS id2, dbo.V2.Product AS Product2, dbo .V2.MonthID AS MonthID2, dbo.V2.Rate AS Rate2 FROM dbo.V1 INNER JOIN dbo.V2 ON dbo.V1.Product = dbo.V2.Product GROUP BY dbo.V1.id, dbo.V1.Product, dbo .V1.MonthID、dbo.V1.Rate、dbo.V2.id、dbo.V2.Product、dbo.V2.MonthID、dbo.V2.Rate
id Product MonthID Rate id2 Product2 MonthID2 Rate2 1 a 201610 13 2 a 201611 22 3 b 201610 29 4 b 201611 14
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.