我需要使用postgresql json计算https://www.chargebee.com/blog/mrr-subscription-businesses-saas-metrics-101/ between selected two dates
中的MRR,同时我的订阅时间间隔为"1 DAY", "15 DAY", "2 WEEK", "X WEEK", "X MONTH", "x YEAR" where x can be any number
我有以下订阅架构和值:
CREATE TABLE subscriptions
(
id bigserial NOT NULL,
data json,
created_date date,
updated_date date,
user_id bigserial NOT NULL,
CONSTRAINT subscription_id_pk PRIMARY KEY (id)
)
数据在列内"数据"以json格式,如:
{
"id": "1",
"amount": 3900,
"interval": "1 WEEK",
"created": 1424011935
}
并且在每个定期订阅成功时创建事务。我认为交易不是必需的,但如果你能用这种方式发展,那么也是好事。
CREATE TABLE transactions
(
id bigserial NOT NULL,
data json,
created_date date,
updated_date date,
user_id bigserial NOT NULL,
CONSTRAINT transactions_id_pk PRIMARY KEY (id)
)
数据在列内"数据"以json格式,如:
{
"id": "1",
"amount": 3900,
"subscription_id": "1"
"created": 1424011935
}
您可以使用表格中的数据json或created_date创建的unix时间戳,以哪个更适合您
答案 0 :(得分:0)
相当简单generate_series
可以与INTERVAL
一起使用,我们可以使用LATERAL JOIN
为每个json行生成数据。
WITH j AS(
SELECT '{
"id": "1",
"amount": 3900,
"interval": "1 WEEK",
"created": 1424011935
}'::json AS data
UNION ALL
SELECT '{
"id": "2",
"amount": 100,
"interval": "23.5 DAY",
"created": 552614400
}'::json
),
dates AS(
SELECT
'2008-03-01 00:00'::timestamp AS start
,'2015-03-08 07:00'::timestamp AS stop
)
SELECT j.data->>'id'
,sum((j.data->>'amount')::int)
,count(*) as intervals
FROM j
CROSS JOIN dates
CROSS JOIN LATERAL
(SELECT i
FROM generate_series(to_timestamp((j.data->>'created')::int), dates.stop + (j.data->>'interval')::interval,(j.data->>'interval')::interval) as i
WHERE i BETWEEN dates.start AND dates.stop
) AS q
GROUP BY j.data->>'id'
上面给出了结果:
id | sum | intervals
----+-------+-----------
1 | 11700 | 3
2 | 11000 | 110