我创建了一个表-
CREATE TABLE sales(year INT, country VARCHAR(20), product VARCHAR(32), profit INT);
在其中插入一些值并尝试使用此查询
SELECT GROUP_CONCAT(country) as country, year, SUM(profit) AS profit
FROM sales
GROUP BY year ASC WITH ROLLUP;
获得的结果-
country | year | profit
----------------------------------------------|-------|----------
India,Australia | 2014 | 50
----------------------------------------------|-------|----------
New Zealand | 2015 | 20
----------------------------------------------|-------|----------
United States | 2016 | 150
----------------------------------------------|-------|----------
India,Australia,New Zealand,United States | NULL | 220
如图所示-最后一行连接所有行值。有没有办法像去年那样用NULL替换最后一行的值?
我需要将
GROUP_CONCAT
用于country
,而不能将groupby
用于country
来获取NULL
。只想用空值替换最后一行的值。 最佳答案
你应该避免汇总
select country, year, profit
from (
SELECT '1' seq, GROUP_CONCAT(country) as country, year, SUM(profit) AS profit
FROM sales
GROUP BY seq, year ;
union
select '2', null, null, SUM(profit)
SELECT
FROM sales
) t
order bt t.seq, t.country
关于mysql - 使用汇总的group_concat弄乱了最后一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45032064/