【问题标题】:Present query data in different format - PostgreSQL以不同格式呈现查询数据 - PostgreSQL
【发布时间】:2018-01-16 07:55:46
【问题描述】:

我的查询以下列方式显示结果:

{"declined": [{"2018-01-16": 1}], "negative": [{"2018-01-16": 1}], "positive": [{"2018-01-16": 2}]}

查询如下所示:

select 
jsonb_build_object('positive', 
  json_agg(jsonb_build_object(date, positive)) FILTER (WHERE positive <> 0)
) ||
jsonb_build_object('negative',
  json_agg( jsonb_build_object(date, negative)) FILTER (WHERE negative <> 0)
) ||
jsonb_build_object('declined', 
  json_agg(jsonb_build_object(date, declined)) FILTER (WHERE declined <> 0)
)
from (
SELECT
  date(survey_results.created_at) as date,
  COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium'))) AS positive,
  COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('low'))) AS negative,
  COUNT(*) FILTER (WHERE (coalesce(raw#>>'{survey,denied}','f') = 'true')) AS declined
  FROM survey_results
  GROUP BY date(survey_results.created_at)
) as t1;

我正在尝试重构该查询以返回如下所示的 json:

{"2018-01-16": {"positive": 2, "declined": "1", "negative": 1}}

我该怎么做?这是您可以尝试的 sql fiddle:

http://sqlfiddle.com/#!17/a9705/8

提前致谢。

【问题讨论】:

标签: sql postgresql postgresql-9.4 jsonb


【解决方案1】:

我可能错过了——我只是在jsonb_build_objectjsonb_build_object

select 
jsonb_build_object(date,jsonb_build_object('positive',positive,'negative',negative,'declined',declined))
from (
SELECT
  date(survey_results.created_at) as date,
  COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('high','medium'))) AS positive,
  COUNT(*) FILTER (WHERE (scores#>>'{medic,social,total}' in('low'))) AS negative,
  COUNT(*) FILTER (WHERE (coalesce(raw#>>'{survey,denied}','f') = 'true')) AS declined
  FROM survey_results
  GROUP BY date(survey_results.created_at)
) t1

结果:

{"2018-01-16": {"declined": 1, "negative": 1, "positive": 2}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2021-09-18
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多