【问题标题】:Need a postgresql query to group in array需要一个 postgresql 查询来分组数组
【发布时间】:2014-12-26 23:16:19
【问题描述】:

我有带日志的表。每条记录都是一个带有应用状态的 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

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

【问题讨论】:

标签: sql postgresql aggregate-functions


【解决方案1】:
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

您的查询结果是一个“表格”,然后我对其进行了分组。

【讨论】:

  • 你按时分组,但我需要按相同“类型”的序列分组。每行的时间开始都不同,因此您根本不分组。请查看示例输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多