gpt4 book ai didi

MYSQL 显示大小写值,即使数据库中不存在该大小写

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

http://sqlfiddle.com/#!9/027e1e/19

此处的示例数据集:

CREATE TABLE IF NOT EXISTS `test` (
`mode` varchar(10),
`value` int(3)
);

INSERT INTO `test` (`mode`, `value`) VALUES
('xx-a', '1'),
('xx-a', '1'),
('xx-c', '2'),
('xx-d', '3');

此处的 SQL 查询:

SELECT CASE 
WHEN mode LIKE '%-a' THEN 'a'
WHEN mode LIKE '%-b' THEN 'b'
ELSE 'c'
END AS channel,
IFNULL(SUM(value), 0)
FROM test
GROUP BY channel

当数据库中不存在值“%-b”时,仅返回包含“a”和“c”的 2 行。我需要它为所有 a、b 和 c 返回 3 行,其中 b 显示 0。

谢谢

最佳答案

解决方案是使用union all:

select 
'a' channel,
sum(case when mode like '%-a' then value else 0 end) sum_value
from mytable
union all select
'b',
sum(case when mode like '%-b' then value else 0 end)
from mytable
union all select
'c',
sum(case when mode not like '%-a' and mode not like '%-b' then value else 0)
from mytable

关于MYSQL 显示大小写值,即使数据库中不存在该大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886238/

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