![](/img/trans.png)
[英]SQL - Select Values From A Table Where A Corresponding Value Matches The Results Of Another Select Statement
[英]Updating a table with multiple values from a select statement where the date matches
我在更新桌子时遇到了问题,我确定它非常直接,但我在这里绕圈转。
我要更新的表'table1'数据格式如下:
[Month] Figure
----------------------------------
2010-05-01 00:00:00.000 1.0000
2010-06-01 00:00:00.000 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.0000
包含更新数字的表'data1'格式如下:
[Month] Figure
----------------------------------
2010-05-01 00:00:00.000 0.7212
2010-08-01 00:00:00.000 1.2351
我正在使用的SQL和错误消息如下。
UPDATE t1
SET t1.figure = (SELECT figure from data1)
FROM table1 t1 JOIN data1 d1
ON (t1.[month] = d1.[month])
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
我需要一个while循环来遍历每一行吗?
我希望最终结果如下:
[Month] Figure
----------------------------------
2010-05-01 00:00:00.000 0.7212
2010-06-01 00:00:00.000 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.2351
非常感激。
UPDATE t1
SET t1.figure = data1.figure
FROM table1 t1 JOIN data1 d1
ON (t1.[month] = d1.[month])
SQL Server 2008:
MERGE INTO Table1
USING data1 AS D1
ON Table1.my_Month = D1.my_Month
WHEN MATCHED
THEN UPDATE
SET Figure = D1.Figure;
Pre-SQL Server 2008:
UPDATE Table1
SET Figure = (
SELECT D1.Figure
FROM data1 AS D1
WHERE Table1.my_Month = D1.my_Month
)
WHERE EXISTS (
SELECT *
FROM data1 AS D1
WHERE Table1.my_Month = D1.my_Month
);
请注意, UPDATE..FROM
语法是专有的,当目标行与多个源行匹配时,可能会产生不可预测的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.