gpt4 book ai didi

mysql - 在sql中合并2行的正确方法是什么

转载 作者:行者123 更新时间:2023-11-29 22:59:22 25 4
gpt4 key购买 nike

所以我有这个名为 test 的表。

A       B   C
dude 10 10
cool 10 10
other 10 10

我想根据 a 列合并 2 行。

所以,如果我太合并“老兄”和“酷”,我最终会得到这样的结果。删除第二个名字。我确实意识到我可能需要进行第二次调用才能删除旧行。

A       B   C
dude 20 20
other 10 10

我认为使用嵌套选择执行更新语句是错误的?

我尝试了类似的方法,看看是否可以合并 b 列。

Update test Set b = al.newb
FROM
(
SELECT b as newb
FROM test WHERE a = "cool"
) al
Where a = "dude";

这里是一个 sql fiddle 调用,用于在需要时创建表。

Create Table test (a varchar(10), b int(3), c int(3));

Insert into test (a, b, c) values ("dude", 10, 10);
Insert into test (a, b, c) values ("cool", 10, 10);
Insert into test (a, b, c) values ("other", 10, 10);

我似乎无法真正发挥任何作用。

最佳答案

您可以通过选择执行您想要的操作:

select (case when a in ('cool', 'dude') then 'dude' else a end) as a,
sum(b) as b, sum(c) as c
from test
group by (case when a in ('cool', 'dude') then 'dude' else a end);

如果您想就地修改数据,更新将不起作用,因为您需要删除一行。我建议将上述查询结果插入到临时表中,截断原始表,然后重新插入所需的行。

关于mysql - 在sql中合并2行的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com