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'的两行。我需要它为所有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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句