简体   繁体   中英

How to update values from one where condition to other where condition on same table and column using SQL

I want to update a column values on different where conditions. below is the example

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

I get rate values as above. Now I want to see these rate column values in the same table on different monthid condition as below

SELECT rate 
FROM dbo.sales 
WHERE monthid = 201611

After update Result:

ID,  Product,  MonthID,   Rate
 2,     a,     201611,     13
 4,     b,     201611,     29

Final Table:

ID,  Product,   MonthID,   Rate
 1,     a,      201610,     13
 2,     a,      201611,     13
 3,     b,      201610,     29
 4,     b,      201611,     29

Is it possible to update rate values from one where condition to another where condition?

update s
set rate = (select rate from dbo.sale where idmonth = 201610 and product = a.product )
from dbo.sales s 
where idmonth = 201611

only works when you have just one recored for each product in each month.

This could helps to update rate values.

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

Create V1(View in sql) : SELECT id, Product, MonthID, Rate FROM dbo.tb1 WHERE (MonthID = 201610)

Create V2(View in sql) : SELECT id, Product, MonthID, Rate FROM dbo.tb1 WHERE (MonthID = 201611)

Create V3(View in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM