Select 使用 postgres 进行小计 sql

Select with subtotals using postgres sql

我有以下查询:

select
    json_build_object('id', i.id, 'task_id', i.task_id, 'time_spent', i.summary)
from
    intervals I
where
    extract(month from "created_at") = 10 
    and extract(year from "created_at") = 2021
group by
    i.id, i.task_id
order by i.task_id 

给出以下输出:

json_build_object
{"id" : 53, "task_id" : 1, "time_spent" : "3373475"}
{"id" : 40, "task_id" : 1, "time_spent" : "3269108"}
{"id" : 60, "task_id" : 2, "time_spent" : "2904084"}
{"id" : 45, "task_id" : 4, "time_spent" : "1994341"}
{"id" : 38, "task_id" : 5, "time_spent" : "1933766"}
{"id" : 62, "task_id" : 5, "time_spent" : "2395378"}
{"id" : 44, "task_id" : 6, "time_spent" : "3304280"}
{"id" : 58, "task_id" : 6, "time_spent" : "3222501"}
{"id" : 48, "task_id" : 6, "time_spent" : "1990195"}
{"id" : 55, "task_id" : 7, "time_spent" : "1984300"}

如何按每个任务添加 time_spent 的小计?

我想要一个像这样的对象数组结构:

{
    "total": 3968600,
    "details:" [
        {"id" : 55, "task_id" : 7, "time_spent" : "1984300"}, 
        {"id" : 55, "task_id" : 7, "time_spent" : "1984300"}
    ]
}

如何实现?谢谢!

您可以尝试进行以下修改,根据 task_id 对数据进行分组并使用 json_agg and json_build_object 生成所需的架构。

select
    json_build_object(
        'total', SUM(i.summary),
        'details',json_agg(
            json_build_object(
                'id', i.id, 
                'task_id', i.task_id, 
                'time_spent', i.summary
             )
         )
      ) as result
from
    intervals I
where
    extract(month from "created_at") = 10 
    and extract(year from "created_at") = 2021
group by
    i.task_id
order by i.task_id 

在线查看工作演示 fiddle here