基于条件选择列

n53p2ov0  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(255)

我有一张类似如下的table:

+---------+--------------+
| 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 .
我在聚合的时候有点困惑。

ffx8fchx

ffx8fchx1#

您需要按类别计算用户数。试试这个

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"

演示

ct2axkht

ct2axkht2#

使用大小写表达式:

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;

相关问题