尝试在使用ROLLUP后订购查询

时间:2014-04-15 19:21:40

标签: mysql sql

在mysql中,我需要按年/月desc命令结果:

Month          Mod1    Mod2    Mod3
Jan/2013        5       4       2
Jan/2013        1       5       3
Total           6       9       5
Feb/2013        6       3       2
Feb/2013        2       1       4
Total           8       4       6
Mar/2014        6       3       2
Mar/2014        2       1       4
Total           8       4       6

按年/月desc排序应为:

Month          Mod1    Mod2    Mod3
Mar/2014        6       3       2
Mar/2014        2       1       4
Total           8       4       6
Feb/2013        6       3       2
Feb/2013        2       1       4
Total           8       4       6
Jan/2013        5       4       2
Jan/2013        1       5       3
Total           6       9       5

查询是:

SELECT
   month,
   year,
   SUM(IF(mod = 1, 1, 0)) AS mod1,
   SUM(IF(mod = 2, 1, 0)) AS mod2,
   SUM(IF(mod = 3, 1, 0)) AS mod3
FROM
   DW_RM_Log
WHERE
   ...
GROUP BY
   year, month
WITH ROLLUP
HAVING year IS NOT NULL AND month IS NOT NULL

我不能在最后插入ORDER BY年,月DESC,因为我收到以下错误:' SQLSTATE [HY000]:常规错误:1221错误使用CUBE / ROLLUP和ORDER BY& #39 ;.有什么建议吗?

2 个答案:

答案 0 :(得分:2)

在MySQL中,group by会进行排序。虽然现在不推荐使用隐式排序,但您仍然可以安全地进行显式排序。以下应该做你想要的:

SELECT month, year,
       SUM(mod = 1) AS mod1, SUM(mod = 2) AS mod2, SUM(mod = 3) AS mod3
FROM DW_RM_Log
WHERE ...
GROUP BY year DESC, month DESC WITH ROLLUP
HAVING year IS NOT NULL AND month IS NOT NULL;

请注意,我还简化了sum()条件。在MySQL中,您可以只使用条件本身,而不是包括if()

答案 1 :(得分:0)

要回答有关在ORDER BY查询上强加WITH ROLLUP的具体问题,您只需将其颠覆为子查询:

SELECT *
FROM
(
SELECT
   month,
   year,
   SUM(IF(mod = 1, 1, 0)) AS mod1,
   SUM(IF(mod = 2, 1, 0)) AS mod2,
   SUM(IF(mod = 3, 1, 0)) AS mod3
FROM
   DW_RM_Log
WHERE
   ...
GROUP BY
   year, month
WITH ROLLUP
HAVING year IS NOT NULL AND month IS NOT NULL
) a 
ORDER BY year, month DESC