如何使用select sum()按组选择值?

时间:2018-09-05 06:31:00

标签: mysql sql database join select

我需要按组选择值(从0到10,从10到50,超过50个)。

user_id     amount
  1           20
  1           40
  2           5
  3           30
  3           1

为什么这个查询不能正常工作?

select (select sum(amount)),
case 
when (select sum(amount))<10 then '0-10' 
when (select sum(amount))>=10 and (select sum(amount))<50 then '10-20' 
else '>50' end as total_amount, count(distinct user_id) 
from table
group by
case 
when (select sum(amount))<10 then '0-10' 
when (select sum(amount))>=10 and (select sum(amount))<50 then '10-20' 
else '>50' end as total_amount, count(distinct user_id);



 output
diapason number_of_users
0-10      1
10-50     1
>50       1

给我提示plz

4 个答案:

答案 0 :(得分:1)

您的查询有很多问题,但是主要由于它不起作用,因为您需要在分类范围之前按用户进行总和。尝试以下方法:

SELECT CASE  
         WHEN amount BETWEEN  0 AND  9 THEN ' 0-10'
         WHEN amount BETWEEN 10 AND 50 THEN '10-50'
         ELSE '>50' END AS diapason,
       COUNT(*) AS number_of_users
FROM (SELECT SUM(amount) AS amount 
      FROM payments 
      GROUP BY user_id) p
GROUP BY diapason;

输出

diapason    number_of_users
0-10        1
10-50       1
>50         1

答案 1 :(得分:0)

尝试以下方式

    select 
    sum(case when amount <10 then 1 else 0 end) as "0-10",
    sum(case when amount >=10 and amount <50 then 1 else 0 end) as "0-50" ,       sum(case when amount>50 then 1 else 0 end) as ">50"   
    from table

答案 2 :(得分:0)

您可以尝试执行此操作,编写一个子查询,以每个SUM获得user_id的金额,然后执行CASE WHEN,在{{1}中不需要select sum(amount) }。

CASE WHEN

查询1

CREATE TABLE t(
   user_id int,
   amount int
);


 insert into t values(1,20);
 insert into t values(1,40);
 insert into t values(2,5);
 insert into t values(3,30);
 insert into t values(3,1);

Results

select 
    case 
        when t1.total<10 then '0-10' 
        when t1.total>=10 and t1.total<50 then '10-50' 
        else '>50' end as diapason, 
    count(distinct user_id) number_of_users
from (
  SELECT user_id,SUM(amount) total
  FROM table
  GROUP BY user_id
) t1
group by 
    case 
        when t1.total<10 then '0-10' 
        when t1.total>=10 and t1.total<50 then '10-50' 
    else '>50' end

答案 3 :(得分:0)

您的语法不正确:

select case 
    when amount<10 then '0-10' 
    when  samount>=10 and amount<50 then '10-20' 
    else '>50' end as total_amount, count(distinct user_id) 
    from table
    group by
    case 
    when amount<10 then '0-10' 
    when  samount>=10 and amount<50 then '10-20' 
    else '>50' end 
相关问题