I need to find a way for the columns in the final results to be set dynamically based on the data in the json query. This is for a Kpi dashboard in grafana. Each outlet might have different KPI measures and I want the dashboard to only show the KPI for the outlet signed in. The below query is showing the data in the format I need it. The rowid will column will stay but the rest of the columns must be dynamic.
Is this possible?
WITH kpi_total AS (
SELECT
order_date || staff_name || outlet_id AS rowid,
kpi_name,
SUM(kpi_cnt) AS total
FROM vw_waiter_kpi_orders wki
GROUP BY order_date || staff_name || outlet_id, kpi_name
),
aggregated_kpi AS (
SELECT
rowid,
jsonb_object_agg(kpi_name, total) AS kpi_data
FROM kpi_total
GROUP BY rowid
)
SELECT
rowid,
kpi_data->>'drinks' AS drinks,
kpi_data->>'extras' AS extras
FROM aggregated_kpi
ORDER BY rowid;