在mysql中联合和汇总

时间:2015-05-13 13:16:05

标签: mysql sql database union 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

提前致谢。

3 个答案:

答案 0 :(得分:0)

你不能这样使用。

你需要做任何一次

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 |
+---------+------+

答案 1 :(得分:0)

你可以用这个

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

答案 2 :(得分:0)

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 |
+---------+------+