mysql - 按组对 "rollup"进行排序

标签 mysql sql

我发现与 group by 一起使用的“with rollup”选项非常有用。但它不适用于“order by”子句。 有什么方法可以按我想要的方式排序并计算小计吗?

CREATE TABLE `mygroup` (
  `id` int(11) default NULL,
  `country` varchar(100) default NULL
) ENGINE=MyISAM ;

INSERT INTO `mygroup` VALUES (1,'India'),(5,'India'),(8,'India'),(18,'China'),(28,'China'),(28,'China');

mysql>select country, sum(id) from mygroup group by country with rollup; 
+---------+---------+
| country | sum(id) |
+---------+---------+
| China   |      74 | 
| India   |      14 | 
| NULL    |      88 | 
+---------+---------+
3 rows in set (0.00 sec)

mysql>select country, sum(id) as cnt from mygroup group by country order by cnt ;
+---------+------+
| country | cnt  |
+---------+------+
| India   |   14 | 
| China   |   74 | 
+---------+------+
2 rows in set (0.00 sec)

mysql>select country, sum(id) as cnt from mygroup group by country with rollup order by cnt;
ERROR 1221 (HY000): Incorrect usage of CUBE/ROLLUP and ORDER BY

Expected Result:
+---------+------+
| country | cnt  |
+---------+------+
| India   |   14 | 
| China   |   74 | 
| NULL    |   88 | 
+---------+---------+
3 rows in set (0.00 sec)

最佳答案

尝试使用临时表

 SELECT * 
 FROM 
 (
     SELECT country, sum(id) as cnt 
     FROM mygroup GROUP BY country WITH rollup
 ) t 
 ORDER BY cnt;

本文可能对您有所帮助link text

关于mysql - 按组对 "rollup"进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1768547/

相关文章:

mysql - 如何配置一个事件mysql从周一到周五每天运行?

java - 获取数据库表的触发器名称

c# - SqlDataReader 和网络延迟

sql - 条件的放置重要吗?

sql - SQL Server 中的日期转换引发错误

SQL 对分区上的不同计数进行累积

mysql 使用主键插入和更新

Mysql 局部变量没有更新

mysql - 计算已完成任务的百分比总计 mysql

php - Laravel/Eloquent 5 事务回滚不支持保存