SQL Server 2017:同时在表中与来自另一个表的数据同时更新2列。
我使用的是Microsoft SQL Server 2017。我使用另一个表中的值更新表的问题存在问题。
我使用以下设置:
表“ main”:
id | val1 | val2 |
---|---|---|
42 | null | null |
表“ val”:
mainid | type | val |
---|---|---|
42 | 1 | 345.67 |
42 | 2 | 567.89 |
,然后我想更新(在1个语句中)在“ main”中的val1和val2列中通过“ val”的值:
UPDATE m
SET m.Val1 = CASE WHEN v.Type = '1' THEN v.Val ELSE m.Val1 END,
m.Val2 = CASE WHEN v.Type = '2' THEN v.Val ELSE m.Val2 END
FROM Main m
INNER JOIN Val v ON m.ID = v.MainID
val1
通过类型1的值应更新为345.67和val2
通过类型2的2 应更新为567.89如下:
表“主”:
ID | Val1 | Val2 |
---|---|---|
42 | 345.67 | 567.89 |
但是,实际结果是:
table“ main”:
id | val1 | val2 |
---|---|---|
42 | 345.67 | null |
我在这里做错了什么?有什么想法吗?
还请在此处利用SQLFIDDLE示例: http://sqlfiddle.com/#!18/ AB9BF0/14
我知道Stackoverflow上已经有许多类似的问题,但是总是做一些稍有不同的事情,因此不幸的是,它们对我没有帮助。如果您发现一个可以解决我的问题的人,我很乐意检查一下。
非常感谢。
I'm using Microsoft SQL Server 2017. I have a problem with an update of a table using values from another table.
I use the following setup:
Table "Main":
ID | Val1 | Val2 |
---|---|---|
42 | NULL | NULL |
Table "Val":
MainID | Type | Val |
---|---|---|
42 | 1 | 345.67 |
42 | 2 | 567.89 |
Then I want to update (in 1 statement) the Val1 and Val2 columns in "Main" with the values from "Val":
UPDATE m
SET m.Val1 = CASE WHEN v.Type = '1' THEN v.Val ELSE m.Val1 END,
m.Val2 = CASE WHEN v.Type = '2' THEN v.Val ELSE m.Val2 END
FROM Main m
INNER JOIN Val v ON m.ID = v.MainID
Val1
via Type 1 should be updated to 345.67 and Val2
via Type 2 should be updated to 567.89, so that the desired result should look as follows:
Table "Main":
ID | Val1 | Val2 |
---|---|---|
42 | 345.67 | 567.89 |
However, the actual result is:
Table "Main":
ID | Val1 | Val2 |
---|---|---|
42 | 345.67 | NULL |
What am I doing wrong here? Any ideas?
Please also take advantage of the SQLFiddle example here: http://sqlfiddle.com/#!18/ab9bf0/14
I know there are many similar questions on Stackoverflow already, but always doing something slightly different, so unfortunately they were of no help to me. If you found one that might solve my issue I'm more than happy to check it out.
Thanks very much in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用子问题。通过查询在子查询中和联接到主表中计算该组
use sub-query. Calculate the GROUP BY query in the sub-query and the join to Main table
一种优雅的方法是使用
pivot
:An elegant way to do it is using
pivot
: