根据条件

时间:2018-05-01 18:27:39

标签: json postgresql aggregate-functions

我在下面的表格中有一个JSON字段

{
"Ui": [
    {
        "element": "TG1",
        "mention": "in",
        "time": 123
    },
    {
        "element": "TG1",
        "mention": "out",
        "time": 125
    },        
    { "element": "TG2",
        "mention": "in",
        "time": 251
    },
    {
        "element": "TG2",
        "mention": "out",
        "time": 259
    }
]
 }

我的意图是得到类似下面的内容

| element  |   Timespent   |
|  TG1     |     2         |
|  TG2     |     8         |

但完全不成功。 我怎样才能得到差异(提及的所有时间的总和 - 当提到的时候所有时间的总和)? 目前我正在尝试sum(jsonb_extract_path(data::jsonb, 'ui','hovers')->0->'when')来获得总和但是无法计算出如何递归查看json文件并过滤提及。

1 个答案:

答案 0 :(得分:2)

使用json_array_elements()从json数组中提取列:

SELECT a.unique_id,
  a.country_code,
  a.rpt_prd,
  a.abv_cut_off_scor_flag,
  a.acct_und_promo_flag,
.
.
  b.arrg_cob_dt,
  b.arrg_id
 from 
 a
inner join 
 b
on a.country_code   = b.country_code
and a.product_code  = b.product_code
and a.rpt_prd       =b.rpt_prd
and a.unique_id     =b.unique_id
and a.arrg_id       = b.arrg_id
WHERE a.country_code='XX'
AND a.product_code  = 'YYYYY'
AND a.rpt_prd       ='20171231' ;

a
======================================
Partition Key for - a
 PARTITIONED BY (                                   |
|   `country_code` string,                           |
|   `product_code` string,                           |
|   `rpt_prd` string,                                |
|   `unique_id` string)  

b
=======================================
 PARTITIONED BY (                                   |
|   `country_code` string,                           |
|   `product_code` string,                           |
|   `rpt_prd` string,                                |
|   `unique_id` string)  



Query using Views:
===================

SELECT a.unique_id,
  a.country_code,
  a.rpt_prd,
  a.abv_cut_off_scor_flag,
  a.acct_und_promo_flag,
.
.
  b.arrg_cob_dt,
  b.arrg_id
from 
 a
inner join 
 b
on a.country_code   = b.country_code
and a.product_code  = b.product_code
and a.rpt_prd       =b.rpt_prd
and a.unique_id     =b.unique_id
and a.arrg_id       = b.arrg_id
WHERE a.country_code='XX'
AND a.product_code  = 'YYYYY'
AND a.rpt_prd       ='20171231' ;

修改上述查询以按元素分组获取总和:

select value->>'element' as element, value->>'time' as time_spent
from my_table
cross join json_array_elements(json_column->'Ui')

 element | time_spent 
-----+------------
 TG1     | 123
 TG1     | 125
 TG2     | 251
 TG2     | 259
(4 rows)

DbFiddle.