2017-10-26 23:38:36 -04:00
|
|
|
|
|
|
|
--this is a dynamic approach that dumps all keys into the json except several that are required which it extracts
|
2017-10-27 01:44:41 -04:00
|
|
|
WITH
|
|
|
|
expand_gl AS (
|
2017-10-26 23:38:36 -04:00
|
|
|
SELECT
|
|
|
|
id,
|
|
|
|
ARRAY['GL',rn::text] json_path,
|
|
|
|
post_stmp,
|
2017-10-27 01:44:41 -04:00
|
|
|
(a.i->>'amt')::numeric amount,
|
2017-10-26 23:38:36 -04:00
|
|
|
a.i->>'account' account,
|
2017-10-27 01:44:41 -04:00
|
|
|
j.rec->'header'->>'date' tran_date,
|
|
|
|
j.rec->'header'->>'vendor' vendor,
|
|
|
|
(a.i - '{amt,account,date}'::text[])||j.rec->'header' as therest
|
2017-10-26 23:38:36 -04:00
|
|
|
FROM
|
2017-10-27 01:44:41 -04:00
|
|
|
evt.log j
|
|
|
|
LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(j.rec->'GL') WITH ORDINALITY a(i, rn) ON TRUE
|
|
|
|
)
|
|
|
|
,gl_agg AS (
|
|
|
|
SELECT
|
|
|
|
id
|
|
|
|
, tran_date
|
|
|
|
, vendor
|
|
|
|
, SUM(amount) amt
|
|
|
|
, ROUND(SUM(amount) FILTER (WHERE account = 'dcard'),2) dr
|
|
|
|
FROM
|
|
|
|
expand_gl
|
|
|
|
GROUP BY
|
|
|
|
id
|
|
|
|
, tran_date
|
|
|
|
, vendor
|
|
|
|
ORDER BY
|
|
|
|
id asc
|
|
|
|
)
|
|
|
|
SELECT id, tran_date, vendor, amt, dr, sum(dr) over(ORDER BY id) FROM gl_agg
|