如何通过几个条件计算范围?

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

我有两张table:

activity
user_id login_time
1       2018-04-15
2       2018-04-18
3       2018-04-19
3       2018-04-20
1       2018-04-20
2       2018-04-20
4       2018-04-20

--

payments
user_id     amount
  1            10
  1            30
  2            100
  3            35
  4            0

我正在寻找的用户数,其中有登录时间=20.04.2018年由格罗普斯。
2018年4月20日的预期结果:

total_amount  number of users
0-10               1
10-20              0
30-50              2
50-and more        1

请帮忙

w7t8yxp5

w7t8yxp51#

这样的方法应该有用:

SELECT CASE WHEN b.amount < 10 THEN '0-10'
  WHEN b.amount < 20 THEN '11-20'
  WHEN b.amount < 30 THEN '21-30'
  WHEN b.amount < 40 THEN '31-40'
  WHEN b.amount < 50 THEN '41-50'
  ELSE '50 and more' END AS total_amount,
  count(DISTINCT b.user_id) AS number_of_users 
FROM activity a
JOIN payments b
ON a.user_id = b.user_id
WHERE a.login_time = '2018-04-18'
GROUP BY 1

如果在活动表中,用户每天只能出现一次,则可以使用count(*)而不是count(不同的用户标识)。
希望有帮助

7d7tgy0s

7d7tgy0s2#

和内部连接时的用例

select case when amount<=10 then '0-10' when amount>10 and amount<20 then '10-20'
when amount>=30 and amount<50 then '30-50'
when amount>=50 then '50-and more' end as total_amount,count(payments.user_id)
from payments inner join activity on payments.user_id=activity.user_id
where login_time='2018-04-20'
group by case when amount<=10 then '0-10' when amount>10 and amount<20 then '10-20'
when amount>=30 and amount<50 then '30-50'
when amount>=50 then '50-and more' end

相关问题