2

我有这个简单的查询,可以计算每月的用户注册数量。

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 回答