基于条件选择列

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

我有一张类似如下的table:

  1. +---------+--------------+
  2. | user_id | distance |
  3. +---------+--------------+
  4. | 101 | 12.05 |
  5. | 103 | 4.8 |
  6. | 207 | 37.1 |
  7. | 991 | 3.51 |
  8. | 215 | 15.9 |
  9. +---------+--------------+

然后我需要覆盖不同距离的用户数: 0-5km 作为 short_distance , 5-10km 作为 medium_distance , >10km 作为 long_distance .
我在聚合的时候有点困惑。

ffx8fchx

ffx8fchx1#

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

  1. select
  2. case
  3. when distance > 10 then 'long_distance'
  4. when distance > 5 then 'medium_distance'
  5. else 'short_distance'
  6. end as "distance_type", count(*) as "Count"
  7. from user_distance
  8. group by "distance_type"

演示

ct2axkht

ct2axkht2#

使用大小写表达式:

  1. select user_id,
  2. case
  3. when distance <= 5 then 'short distance'
  4. when distance <= 10 then 'medium distance'
  5. else 'long distance'
  6. end as what
  7. from the_table;

相关问题