需要postgresql查询才能在数组中分组

时间:2014-12-26 23:16:20

标签: sql postgresql aggregate-functions

我有日志表。每条记录都是一个带有app状态的json数组。

create table tail (record json);
--
insert into tail values (
    '[{"type":"p1","app":"mxx","timestart":"09:00:20","duration":10},
    {"type":"p2","app":"sxx","timestart":"09:20:30","duration":180},
    {"type":"p2","app":"sxx","timestart":"09:25:00","duration":25},
    {"type":"p1","app":"sxx","timestart":"09:27:10","duration":130},
    {"type":"p2","app":"cxx","timestart":"09:40:40","duration":2},
    {"type":"p3","app":"mxx","timestart":"09:41:20","duration":2},
    {"type":"p3","app":"axx","timestart":"09:41:30","duration":245},
    {"type":"p3","app":"dxx","timestart":"09:50:55","duration":7},
    {"type":"p2","app":"mxx","timestart":"10:10:02","duration":1}]'
);

我需要以下结果:

----------------------
--type| timestart| sum(duration)
----------------------
-- p1 | 09:00:20 | 10
-- p2 | 09:20:30 | 205
-- p1 | 09:27:10 | 130
-- p2 | 09:40:40 | 2
-- p3 | 09:41:20 | 254
-- p2 | 10:10:02 | 1
-----------------------

__

sqlfiddle.com

可能以及如何?非常感谢你!

1 个答案:

答案 0 :(得分:0)

select *, sum(t.int4)
from (
with data as 
(
    select
        json_array_elements(record) as "r"
    from tail
)
select
  r->>'type' as type,CAST(r->>'timestart' as time),cast(r->>'duration' as int)
from data) as t
group by t.time, t.type, t.int4

您的查询结果是"表"然后我就分组了。