[英]Update a table in SQL Server 2008 R2 by a column in another table and also need a sum value
I am trying to update a table in SQL Server 2008 R2. 我正在尝试更新SQL Server 2008 R2中的表。
Table1: 表格1:
id name value1
a 34 3
a 32 2
a - -
c 90 9
Table2: 表2:
id
a
expected table1: 预期表1:
id name value1
a 34 3
a 32 2
a - 5
c 90 9
I need to sum all value1 group by id that exists in table2. 我需要按表2中存在的ID对所有value1组进行求和。
My SQL query: 我的SQL查询:
update table1
set value1 = cast(SUM(cast ([value1] as float)) as varchar(50))
GROUP BY id
where name = '-' and id in
(
select distinct id
from table2
)
I got error: 我收到错误消息:
Incorrect syntax near the keyword 'GROUP'. 关键字“ GROUP”附近的语法不正确。
Any help would be appreciated. 任何帮助,将不胜感激。
UPDATE 更新
update table1
set value1 = cast(SUM(cast ([value1] as float)) as varchar(50))
where name = '-' and id in
(
select distinct id
from table2
)
GROUP BY id
still : 仍然:
Incorrect syntax near the keyword 'GROUP'.
You can't use that construct afaik. 您不能使用该构造afaik。 You need a subquery to calculate your values based on id, and update
from that table: 您需要一个子查询来根据id计算值,并从该表进行update
:
UPDATE table1
SET value1 = SumTable.val
FROM (
SELECT T1.id, cast(SUM(cast (T1.[value1] as float)) as varchar(50)) as val
FROM table1 T1
WHERE T1.id in
(
select distinct T2.id
from table2 T2
)
GROUP BY T1.id
) AS SumTable
WHERE table1.id = SumTable.id
If you just want to return the grouped result, you can do this by running the following 如果只想返回分组结果,可以通过运行以下命令来完成
SELECT ID, SUM(Value)
FROM Table1
WHERE ID IN (SELECT ID FROM Table2) GROUP BY ID
If, however, you want to replace the contents of table1, there's no trivial way of doing this in a single operation. 但是,如果要替换table1的内容,则没有简单的方法可以在单个操作中执行此操作。 You need 'cache' the intermediate result before recreating the original table: 在重新创建原始表之前,需要“缓存”中间结果:
DECLARE @TEMPTABLE TABLE (ID int, Value int);
INSERT INTO @TEMPTABLE SELECT ID, SUM(Value)
FROM Table1
WHERE ID IN (SELECT ID FROM Table2) GROUP BY ID
DROP TABLE Table1
SELECT * INTO Table1 FROM @TempTable
SELECT * FROM TABLE1
(note, that was from your first edit) (请注意,这是您的第一次编辑)
If you just want to add additional 'sum' lines to the table, then you should be able to avoid the temp table and instead issue an INSERT INTO
statement using the SELECT
statement I gave first as a sub-query. 如果只想向表中添加其他“求和”行,则应该能够避免使用temp表,而应使用我首先作为子查询提供的SELECT
语句来发出INSERT INTO
语句。
I do think what you're doing is quite strange, however, and you may want to think about what you're doing with your tables. 我确实认为您正在做的事情很奇怪,但是您可能想考虑一下您对表所做的事情。
Your casting back to a VARCHAR is also a little strange - if they're always going to be an integer, keep them as integers. 强制转换回VARCHAR也有点奇怪-如果它们始终是整数,请将其保留为整数。 If they're truly VARCHARS then SUM won't always work 如果它们是真正的VARCHARS,那么SUM并不总是有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.