根据条件选择列

时间:2020-05-29 10:09:32

标签: sql postgresql aggregate

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

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

然后,我想要覆盖不同距离范围的用户数量:0-5kmshort_distance5-10kmmedium_distance>10km为{{1 }}。

聚集时我有点困惑。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

您希望明智地分类用户数。试试这个

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

相关问题