我有一个类似于以下表格:
+---------+--------------+
| user_id | distance |
+---------+--------------+
| 101 | 12.05 |
| 103 | 4.8 |
| 207 | 37.1 |
| 991 | 3.51 |
| 215 | 15.9 |
+---------+--------------+
然后我想要覆盖不同距离范围的用户数量:0-5km
设为short_distance
,5-10km
设为medium_distance
,>10km
设为long_distance
。
聚集时我有点困惑。
使用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;
您需要明智地分类用户数。试试这个
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"