繁体   English   中英

如何使用 SQL 将同一表和列上的值从一个 where 条件更新到另一个 where 条件

[英]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.

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