admin

在状态级别计算特定存储桶中的行数

sql

我有一张桌子,如下。它提供有关user_id,其状态和订阅数量的信息,如下所示

+---------+-------+---------------+
| user_id | State | Subscriptions |
+---------+-------+---------------+
|       1 | LA    |             4 |
|       2 | LA    |             4 |
|       3 | LA    |            12 |
|       4 | LA    |            12 |
|       5 | LA    |             8 |
|       6 | LA    |             3 |
|       7 | NY    |            14 |
|       8 | NY    |            15 |
|       9 | NY    |             3 |
|      10 | NY    |             2 |
|      11 | NY    |             4 |
|      12 | NY    |            12 |
|      13 | OH    |             6 |
|      14 | OH    |             8 |
|      15 | OH    |             2 |
|      16 | OH    |             3 |
+---------+-------+---------------+

我想以如下方式转换数据,即希望每个存储桶处于状态级别的记录数如下:

+--------------------+----+----+----+
| Subscription_Range | LA | NY | OH |
+--------------------+----+----+----+
| 1 to 4             |  3 |  3 |  2 |
| 5 to 11            |  1 |  0 |  2 |
| 12 to 15           |  2 |  3 |  0 |
+--------------------+----+----+----+

任何帮助将不胜感激。

sqlfiddle


阅读 152

收藏
2021-06-07

共1个答案

admin

您可以使用case和条件聚集:

select (case when subscriptions <= 4 then '1 to 4'
             when subscriptions <= 11 then '5 to 11'
             when subscriptions <= 15 then '12 to 15'
        end) as subscription_range,
       sum(case when state = 'LA' then 1 else 0 end) as LA,
       sum(case when state = 'NY' then 1 else 0 end) as NY,
       sum(case when state = 'OH' then 1 else 0 end) as OH
from t
group by (case when subscriptions <= 4 then '1 to 4'
               when subscriptions <= 11 then '5 to 11'
               when subscriptions <= 15 then '12 to 15'
          end)
order by min(subscriptions);
2021-06-07