PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Calcular o resultado de receita recorrente mensal (MRR) usando postgres


É bem simples generate_series pode ser usado com INTERVAL s e podemos usar um LATERAL JOIN para gerar os dados para cada linha 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'

O acima nos dá o resultado:
 id |  sum  | intervals
----+-------+-----------
 1  | 11700 |         3
 2  | 11000 |       110

SQLFiddle