【问题标题】:union and rollup in mysqlmysql中的联合和汇总
【发布时间】:2015-05-13 13:16:05
【问题描述】:

当我将标头与使用汇总构造的实际数据合并以将它们写入 .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

提前致谢。

【问题讨论】:

    标签: mysql sql database union rollup


    【解决方案1】:
    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 |
    +---------+------+
    

    【讨论】:

    • 感谢弗拉德米尔!这正是我想要的。但我不明白,我给出的查询是如何不起作用的,除了使用括号将单个查询分成子查询之外,它实际上做了同样的事情。有什么见解吗?
    【解决方案2】:

    你不能用这种方式。

    你需要做任何一个

    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 IFNULL(item, 'TOTAL') AS item, SUM(value) AS tot FROM products GROUP BY item WITH ROLLUP;
    【解决方案3】:

    你可以用这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 2023-01-14
      • 1970-01-01
      • 2016-07-06
      • 2017-04-05
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多