嘗試獲取顯示從一個月到下一個月的保留期的基本表。所以如果上個月有人購買了東西,而且他們在下個月這樣做,那麼它就會被計算在內。如何使用SQL計算每月的保留月份
month, num_transactions, repeat_transactions, retention
2012-02, 5, 2, 40%
2012-03, 10, 3, 30%
2012-04, 15, 8, 53%
所以,如果每個人上個月買再買下一個月你有100%。
到目前爲止,我只能手動計算東西。這給了我已經看到了這兩個月的行:
select count(*) as num_repeat_buyers from
(select distinct
to_char(transaction.timestamp, 'YYYY-MM') as month,
auth_user.email
from
auth_user,
transaction
where
auth_user.id = transaction.buyer_id and
to_char(transaction.timestamp, 'YYYY-MM') = '2012-03'
) as table1,
(select distinct
to_char(transaction.timestamp, 'YYYY-MM') as month,
auth_user.email
from
auth_user,
transaction
where
auth_user.id = transaction.buyer_id and
to_char(transaction.timestamp, 'YYYY-MM') = '2012-04'
) as table2
where table1.email = table2.email
這是不對的,但我覺得我可以用一些Postgres的窗口功能。請記住,窗口函數不允許指定WHERE子句。你大多可以訪問以前的行與前行:在閱讀之後,從減1個月更改爲加1月份:
select month, count(*) as num_transactions, count(*) over (PARTITION BY month ORDER BY month)
from
(select distinct
to_char(transaction.timestamp, 'YYYY-MM') as month,
auth_user.email
from
auth_user,
transaction
where
auth_user.id = transaction.buyer_id
order by
month
) as transactions_by_month
group by
month
'repeat_transactions'從哪裏來?你能發表表格定義嗎?或者,甚至可能是http://sqlfiddle.com上的一個小樣本 – 2013-05-11 09:19:02
要獲得準確答案,此問題需要樣本數據。 – 2013-05-11 09:54:42