在ORDER BY上使用汇总的问题

时间:2018-09-06 07:52:08

标签: mysql sql database join select

我有一个查询:

SELECT IFnull(t.diapason,'total') as diapason, COUNT(distinct user_id) AS 
'number_of_users'
FROM (SELECT p.user_id, p.amount as total, CASE  
    when amount<=100 then '0-100' 
when amount>100 and amount<=150 then '100-150' 
when amount>150 then '>150 +' END AS diapason
    FROM 
        (SELECT payments.user_id, SUM(amount) AS amount 
       FROM payments INNER JOIN (SELECT DISTINCT user_id FROM activity where 
login_time between '2018-04-12' and '2018-04-18') a ON payments.user_id = 
a.user_id
             GROUP BY payments.user_id) p) t
GROUP BY diapason WITH ROLLUP
 ORDER BY number_of_users desc;

如果我进行此查询,则会收到消息:

ERROR 1221 (HY000): Incorrect usage of CUBE/ROLLUP and ORDER BY

但是,如果我在不使用ORDER BY的情况下将其设为男性,则可以使用。但是我需要按顺序排列结果。

我该怎么办?

2 个答案:

答案 0 :(得分:1)

使用子查询进行排序

  select t1.* from   
(
SELECT IFnull(t.diapason,'total') as diapason, COUNT(distinct user_id) AS 
    'number_of_users'
    FROM (SELECT p.user_id, p.amount as total, CASE  
        when amount<=100 then '0-100' 
    when amount>100 and amount<=150 then '100-150' 
    when amount>150 then '>150 +' END AS diapason
        FROM 
            (SELECT payments.user_id, SUM(amount) AS amount 
           FROM payments INNER JOIN (SELECT DISTINCT user_id FROM activity where 
    login_time between '2018-04-12' and '2018-04-18') a ON payments.user_id = 
    a.user_id
                 GROUP BY payments.user_id) p) t
    GROUP BY diapason WITH ROLLUP
) as t1 ORDER BY t1.number_of_users desc;

答案 1 :(得分:0)

正如我在上一个问题中提到的那样,有一种更好的方法可以做到这一点,即假设大多数范围是均匀分布的(例如,以50、100等为块),对范围值的硬编码要少得多

+---------+--------+
| user_id | amount |
+---------+--------+
|       1 |    300 |
|       1 |    100 |
|       2 |    100 |
|       2 |    100 |
|       3 |     10 |
|       4 |    200 |
+---------+--------+
6 rows in set (0.00 sec)

select rng, obs
from
(
select 't' as src,
         case when amount < 100 then '0-99'
               when amount > 150 then '> 150'
         else
         concat(floor(amount/50) * 50 , '-' ,floor(amount/50) * 50  + 49) 
         end as rng,
         count(*) obs
from t
group by src,rng
) a
union       select  'Total' rng, count(*) from t
group by  rng;

在这里使用底数计算得出范围值的大部分,简单的并集就可以计算出总数。

+---------+-----+
| rng     | obs |
+---------+-----+
| 0-99    |   1 |
| 100-149 |   3 |
| > 150   |   2 |
| Total   |   6 |
+---------+-----+
4 rows in set (0.01 sec)

如果您需要填写表格中不存在的范围值,请参见https://dba.stackexchange.com/questions/68791/group-by-in-ranges了解建议的方法。