【问题标题】:How to calculate ranging by a few conditions?如何通过几个条件计算测距?
【发布时间】:2019-02-09 11:01:40
【问题描述】:

我有 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

我正在寻找用户的数量,其 login_time = 20.04.2018 by grops。

2018 年 4 月 20 日的预期结果:

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

请帮忙

【问题讨论】:

    标签: mysql database join select histogram


    【解决方案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
    

    【讨论】:

    • 是的,有一个拼写错误,我已更正,您现在可以查看
    • 你能解决吗,因为空集,好吗?
    • 请让我检查一下
    • 是的,我看到了。但是你怎么想,为什么它在我的电脑上显示空集?
    【解决方案2】:

    这样的事情应该可以工作:

    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)。

    希望对你有帮助

    【讨论】:

    • ERROR 1052 (23000): 字段列表中的列 'user_id' 不明确 mysql>
    猜你喜欢
    • 2020-12-05
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2016-05-11
    • 2018-08-26
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多