使用按顺序汇总的问题

wdebmtf2  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(271)

我有个问题:

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

但如果我不按命令把它弄成雄性,它就行了。但我需要结果。
我该怎么办?

gcmastyq

gcmastyq1#

正如我在上一个关于这个主题的问题中所说的,有一种更好的方法可以做到这一点,即假设大多数范围都是均匀分布的(即以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;

在这里,使用floor计算出大部分范围值,一个简单的并集计算总值。

+---------+-----+
| 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 建议的方法。

kkih6yb8

kkih6yb82#

使用子查询do order by

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;

相关问题