mysql 中的合并和汇总

union and rollup in mysql

当我将 headers 与使用 rollup 构建的实际数据合并以将它们写入 .csv 文件时,我找不到导致此错误的原因。

CREATE TABLE `products` (
`id` int(11) default NULL,
`item` varchar(100) default NULL,
`value` int(11) default NULL
) ENGINE=MyISAM ;

INSERT INTO `products` VALUES (1,'Mobiles', '1000'),(5,'Mobiles', '2000'),(8,'Mobiles', 4000),(18,'Books',100),(28,'Books', 200),(28,'Books',400);

当我尝试下面的查询时,

 SELECT * FROM (
    (SELECT 'ITEM', 'SUM')
    UNION
    (select item, sum(value) from products group by item with rollup)
) data;

我收到这个错误

ERROR 1221 (HY000): Incorrect usage of CUBE/ROLLUP and ORDER BY

提前致谢。

您不能使用这种方式。

您需要执行任一操作

select item, sum(value) from products group by item with rollup;

select item, sum(value) as tot from products group by item
union all
select 'ITEM',sum(value) from products

第一次查询结果为

+---------+------------+
| item    | sum(value) |
+---------+------------+
| Books   |        700 |
| Mobiles |       7000 |
| NULL    |       7700 |
+---------+------------+

和第二个

+---------+------+
| item    | tot  |
+---------+------+
| Books   |  700 |
| Mobiles | 7000 |
| ITEM    | 7700 |
+---------+------+

你可以使用这个

 SELECT * FROM ( select item as 'ITEM', sum(value) as 'SUM'
              from products group by item with rollup) as data 
select 'ITEM', 'SUM'
union
select item, sum(value) from products group by item with rollup
;

结果:

+---------+------+
| ITEM    | SUM  |
+---------+------+
| ITEM    | SUM  |
| Books   | 700  |
| Mobiles | 7000 |
| NULL    | 7700 |
+---------+------+