【问题标题】:SELECT column based on conditions根据条件选择列
【发布时间】:2020-05-29 10:09:32
【问题描述】:

我有一个类似于以下的表格:

+---------+--------------+
| user_id | distance     |
+---------+--------------+
|     101 | 12.05        |
|     103 | 4.8          |
|     207 | 37.1         |
|     991 | 3.51         |
|     215 | 15.9         |
+---------+--------------+

然后我想要覆盖不同距离范围的用户数量:0-5km as short_distance, 5-10km as medium_distance, >10km as long_distance

我在汇总时有点困惑。

【问题讨论】:

    标签: sql postgresql aggregate


    【解决方案1】:

    使用 CASE 表达式:

    select user_id, 
           case 
             when distance <= 5 then 'short distance'
             when distance <= 10 then 'medium distance'
             else 'long distance'
           end as what
    from the_table;
    

    【讨论】:

    • @a_horse_with_no_name 谢谢。我对聚合感到困惑。
    【解决方案2】:

    您希望明智地计算用户类别。试试这个

    select 
           case 
             when distance > 10 then 'long_distance'
             when distance > 5  then 'medium_distance'
             else 'short_distance'
          end as "distance_type", count(*) as "Count"
    from user_distance
    
    group by "distance_type"
    

    DEMO

    【讨论】:

    • @谢谢。有没有一种方法可以计算这是我现在的情况,比如 100 个用户覆盖
    • 你想要这样的DEMO
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2016-11-02
    • 2013-12-27
    • 2016-09-16
    • 2013-06-02
    相关资源
    最近更新 更多