2014-12-26 20 views
-1

我有帶日誌的表。每條記錄都是具有應用程序狀態的json數組。需要postgresql查詢才能在數組中組

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

是可能的,怎麼樣?非常感謝你!

+0

閱讀http://www.postgresql.org/docs/9.4/static/functions-json.html –

+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 

查詢結果是一個「表」,然後我對它進行分組。

+0

您按時按組,但我需要在相同「類型」的序列。 Timestarts在每一行都不同,所以你根本就不會組隊。請看看示例輸出。 –

相關問題