Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 分组到json数组中_Sql_Postgresql - Fatal编程技术网

Sql 分组到json数组中

Sql 分组到json数组中,sql,postgresql,Sql,Postgresql,使用Postgres 9.5 对于每个应用程序,我试图计算有多少对话是从由started\u at\u url列所值的各种url启动的 我能得到这样的结果 id: 1, ..., data: {"urls" : ["/","/insights","/signin"], "counts" : [1,2,2]} 但它更希望有一个JSON对象数组,其形式为{url,count} 到目前为止,我的问题是: select dt.id as app_id, json_build_objec

使用Postgres 9.5

对于每个
应用程序
,我试图计算有多少
对话
是从由
started\u at\u url
列所值的各种url启动的

我能得到这样的结果

id: 1, ..., data: {"urls" : ["/","/insights","/signin"], "counts" : [1,2,2]}
但它更希望有一个JSON对象数组,其形式为
{url,count}

到目前为止,我的问题是:

select
    dt.id as app_id,
    json_build_object(
        'urls', array_agg(dt.started_at_url),
        'counts', array_agg(dt.count)
    ) as data
from (
    select a.id, c.started_at_url, count(c.id) 
    from apps a
    left join conversations c on c.app_id = a.id
    where started_at_url is not null and c.started_at::date > (current_date - (7  || ' days')::interval)::date
    group by a.id, c.started_at_url
) as dt
group by dt.id
有什么建议吗

谢谢

为什么不使用

array_agg(
   json_build_object(
      'url', dt.started_at_url,
      'count', dt.count
   )
)
而不是

json_build_object(
   'urls', array_agg(dt.started_at_url),
   'counts', array_agg(dt.count)
)