JSON_AGG作为对象而不是数组-PostgreSQL

qco9c6ql  于 12个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(318)

我有一个表“mytable”,其中有许多“坏”和“好”记录:

|id|good|hour |
|1 |t   |12:00|
|2 |f   |12:00|
|3 |t   |13:00|
|4 |t   |13:00|
|5 |t   |13:00|
|6 |f   |14:00|
....

字符串
我当前的查询是:

SELECT 
    h, 
    JSON_AGG(data) 
FROM (
    hour AS h, 
    JSON_BUILD_OBJECT(CASE WHEN good = TRUE THEN 'good' ELSE 'bad' END, COUNT(*)) AS data 
    FROM mytable 
    GROUP BY h, good
) AS foo 
GROUP BY h 
ORDER BY h;


我得到的结果是:

12:00 | [{"good" : 1}, {"bad" : 1}]
 13:00 | [{"good" : 3}]
 14:00 | [{"bad" : 1}]
 ...


但我想要的结果是:

12:00 | {"good" : 1, "bad" : 1}
 13:00 | {"good" : 3, "bad" : 0}
 14:00 | {"good" : 0, "bad" : 1}
 ...


有没有办法得到它(合并两个JSON对象合并成一个)?谢谢!

gkl3eglg

gkl3eglg1#

json_build_object()只有一个聚合级别就足够了:

select 
    hour as h,
    json_build_object(
        'good',
        count(*) filter (where good = true),
        'bad',
        count(*) filter (where good = false)
    ) js
from mytable
group by hour
order by hour

字符串

Demo on DB Fiddle

h     | js                     
:---- | :----------------------
12:00 | {"good" : 1, "bad" : 1}
13:00 | {"good" : 3, "bad" : 0}
14:00 | {"good" : 0, "bad" : 1}

y0u0uwnf

y0u0uwnf2#

尝试用JSON_BUILD_OBJECT替换JSON_AGG。这应该会有帮助!

ki1q1bka

ki1q1bka3#

如果你使用json_build_object,你将不得不手动输入每个字段,所以你可以使用to_json,json对象(不带数组)将自动生成,希望对某人有用

相关问题