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

I need to find a way for the columns in the final results to be set dynamically based on the data in th

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;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744331961a4568929.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信