我发现与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)发布于 2009-11-20 13:49:10
尝试使用临时表
SELECT *
FROM
(
SELECT country, sum(id) as cnt
FROM mygroup GROUP BY country WITH rollup
) t
ORDER BY cnt;这篇文章可能对你link text有帮助。
发布于 2012-09-26 01:20:02
您试过将订单放入分组中吗?
SELECT country, SUM(id)
FROM mygroup
GROUP BY country DESC WITH ROLLUP;应返回:
+---------+---------+
| country | SUM(id) |
+---------+---------+
| India | 14 |
| China | 74 |
| NULL | 88 |
+---------+---------+http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html
发布于 2015-11-02 15:43:44
您可以尝试执行以下查询:
SELECT country,id
FROM mygroup GROUP BY country ASC WITH ROLLUPhttps://stackoverflow.com/questions/1768547
复制相似问题