price_api/sql/gethist.sql

66 lines
1.7 KiB
PL/PgSQL

CREATE OR REPLACE FUNCTION rlarp.gethist(_item text, _cust text)
RETURNS jsonb
LANGUAGE plpgsql
AS $func$
DECLARE
result jsonb;
BEGIN
WITH getj AS (
SELECT jsonb_build_object('mold',_item,'cust',_cust) doc
--SELECT (
-- SELECT jsonb_build_object('mold', JSON_AGG(DISTINCT stlc))
-- FROM "CMS.CUSLG".itemm
-- WHERE item ~ _item
--) || (
-- SELECT jsonb_build_object('cust', JSONB_AGG(DISTINCT c.dba))
-- FROM rlarp.cust c
-- WHERE c.dba ~ _cust
--) AS doc
),
agg AS (
SELECT
gset,
(SELECT string_agg(ae.v, '.') FROM jsonb_array_elements_text(p.agglevel) ae(v)) AS agglvl,
season,
stats,
(SELECT doc FROM getj) AS gdoc
FROM
rlarp.price_pool_dev p
WHERE
gset @> jsonb_build_object(
'mold', (SELECT doc->>'mold' FROM getj),
'vers', 'A'
)
AND (
gset @> jsonb_build_object(
'cust', (SELECT doc->>'cust' FROM getj)
)
OR NOT gset ? 'cust'
)
ORDER BY agglevel ASC
),
aggfinal AS (
SELECT
jsonb_build_object(
agg.agglvl,
jsonb_agg(gset || jsonb_build_object('season', season,'stats',stats))
) AS data,
gdoc
FROM agg
GROUP BY agglvl, gdoc
),
final AS (
SELECT
public.jsonb_obj_aggc(data) AS data,
gdoc
FROM aggfinal
GROUP BY gdoc
)
SELECT data INTO result FROM final;
RETURN result;
END
$func$;