根据条件选择的列

问题描述 投票:0回答:2

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

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

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

聚集时我有点困惑。

sql postgresql aggregate
2个回答
3
投票

使用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;

0
投票

您需要明智地分类用户数。试试这个

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

© www.soinside.com 2019 - 2024. All rights reserved.