我有2张桌子:
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的用户数量。
期望的结果于20.04.2018:
total_amount number of users
0-10 1
10-20 0
30-50 2
50-and more 1
请帮忙
用例何时和内连接
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
这样的事情应该有效:
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(DISTINCT user_id)。
希望能帮助到你