2

1 か月あたりのユーザー登録数を計算するこの簡単なクエリがあります。

SELECT TO_CHAR(created_at, 'YYYY-MM') AS month, COUNT(user_id)
FROM users
GROUP BY month
ORDER BY month DESC 

私が知りたいのは、毎月の前月と比較したパーセンテージの成長です。

4

2 に答える 2

6

SQL フィドル

select
    month, total,
    (total::float / lag(total) over (order by month) - 1) * 100 growth
from (
    select to_char(created_at, 'yyyy-mm') as month, count(user_id) total
    from users
    group by month
) s
order by month;
  month  | total |      growth      
---------+-------+------------------
 2013-01 |     2 |                 
 2013-02 |     3 |               50
 2013-03 |     5 | 66.6666666666667
于 2013-05-03T11:36:47.640 に答える
2

SQL フィドル

PostgreSQL 9.1.9 スキーマのセットアップ:

create table users (created_at date, user_id int);
insert into users select '20130101', 1;
insert into users select '20130102', 2;
insert into users select '20130203', 3;
insert into users select '20130204', 4;
insert into users select '20130201', 5;
insert into users select '20130302', 6;
insert into users select '20130303', 7;
insert into users select '20130302', 8;
insert into users select '20130303', 9;
insert into users select '20130303', 10;

クエリ 1 :

select
  month,
  UserCount,
  100 - lag(UserCount) over (order by month asc)
        * 100.0 / UserCount Growth_Percentage
from
(
  SELECT TO_CHAR(created_at, 'YYYY-MM') AS month,
         COUNT(user_id) UserCount
  FROM users
  GROUP BY month
  ORDER BY month DESC
) sq

結果

|   MONTH | USERCOUNT | GROWTH_PERCENTAGE |
-------------------------------------------
| 2013-01 |         2 |            (null) |
| 2013-02 |         3 |   33.333333333333 |
| 2013-03 |         5 |                40 |

Clodoaldoは正しいです。成長率は ( Fiddle2 )を使用して計算する必要があります。

  100.0 * UserCount
        / lag(UserCount) over (order by month asc)
        - 100
        AS Growth_Percentage
于 2013-05-03T11:37:51.283 に答える