最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json - Using jsonb_object_agg to pivot data but need to columns to be set dynamically - Stack Overflow

programmeradmin5浏览0评论

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;
发布评论

评论列表(0)

  1. 暂无评论