2017-01-19 123 views
0

我有表,這樣的價值jsonb領域:如何聚合jsonb對象?

{ 
"1":[{"start":64800,"finish":68400},{"start":61200,"finish":64800},{"start":75600,"finish":79200},{"start":79200,"finish":82800}], 
"2":[{"start":68400,"finish":72000},{"start":72000,"finish":75600},{"start":75600,"finish":79200},{"start":79200,"finish":82800}], 
"3":[{"start":46800,"finish":50400},{"start":50400,"finish":54000}], 
"4":[{"start":50400,"finish":54000}], 
"5":[{"start":79200,"finish":82800},{"start":82800,"finish":0},{"start":0,"finish":3600}], 
"6":[{"start":68400,"finish":72000},{"start":72000,"finish":75600},{"start":79200,"finish":82800}] 
} 

0 ... 6 - 一週中的一天,這是工作時間的陣列。

所以我需要將工作時間按周計算。例如,一個行有

"5":[{"start":79200,"finish":82800},{"start":82800,"finish":0},{"start":0,"finish":3600}]

另一行有

"5":[{"start":75600,"finish":79200}]

,我想

"5":[{"start":75600,"finish":79200},{"start":79200,"finish":82800},{"start":82800,"finish":0},{"start":0,"finish":3600}]

+2

這將是一個正確的規範化的數據模型SOOOO簡單 –

+0

第一個數據集只有一排與所有這些價值?或者每一行都是數據庫中的一行? –

+0

什麼是Postgresql版本? –

回答

0

如果需要此報告可以手動運行不規則地,&,你可以這樣做within PostgreSQL本身。但是如果性能對你很重要,你應該規範你的模式(如果你的jsonb列的結構很簡單,根本就不需要使用JSON:你沒有任何非結構化數據)。

SELECT jsonb_object_agg(dow, working_times_agg) 
FROM (SELECT  dow, jsonb_agg(working_time) working_times_agg 
     FROM  table t, 
        jsonb_each(t.jsonb_column) o(dow, working_times), 
        jsonb_array_elements(working_times) working_time 
     GROUP BY dow) working_times_agg_by_dow