我的查询以下列方式显示结果:
{"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小提琴:
http://sqlfiddle.com/#!17/a9705/8
提前致谢。
答案 0 :(得分:1)
我可能错过了什么 - 我jsonb_build_object
只是jsonb_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}}