我有這個簡單的查詢計算每月用戶註冊的數量。SQL查詢:用戶每月增長的百分比
SELECT TO_CHAR(created_at, 'YYYY-MM') AS month, COUNT(user_id)
FROM users
GROUP BY month
ORDER BY month DESC
我想要的是每個月的增長百分比與前一個月相比。
我有這個簡單的查詢計算每月用戶註冊的數量。SQL查詢:用戶每月增長的百分比
SELECT TO_CHAR(created_at, 'YYYY-MM') AS month, COUNT(user_id)
FROM users
GROUP BY month
ORDER BY month DESC
我想要的是每個月的增長百分比與前一個月相比。
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
的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 |
Clodo阿爾是正確的,增長比例應使用(Fiddle2)
100.0 * UserCount
/lag(UserCount) over (order by month asc)
- 100
AS Growth_Percentage
您正在計算的是所謂的_商業利潤率_或_利潤率__。我想這不是OP要求的。 3超過2是50%增長不是33.3 – 2013-05-03 11:47:30
你是絕對正確的!正在考慮利潤率.. – RichardTheKiwi 2013-05-03 11:58:15
非常感謝!我接受了Clodoaldo Neto的回答,因爲他/她是第一個,但這也是正確的答案。 – 2013-05-03 13:36:24
這是嚴重的真棒來計算!非常感謝! – 2013-05-03 13:32:25