Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于条件从json数组中提取的求和值_Json_Postgresql_Aggregate Functions - Fatal编程技术网

基于条件从json数组中提取的求和值

基于条件从json数组中提取的求和值,json,postgresql,aggregate-functions,Json,Postgresql,Aggregate Functions,我在下面的表格中有一个JSON字段 { "Ui": [ { "element": "TG1", "mention": "in", "time": 123 }, { "element": "TG1", "mention": "out", "time": 125 }, { "element": "TG2", "mention": "i

我在下面的表格中有一个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         |
我的目的是得到下面这样的东西

{
"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\u extract\u path(data::jsonb,'ui','hover')->0->'when')
来获取sum,但无法理解如何递归地查看json文件并进行过滤。

用于从json数组中提取列:

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)
修改上述查询以按元素分组获取总和:

select element, sum(time) as time_spent
from my_table
cross join lateral (
  select
    value->>'element' as element,
    case value->>'mention' when 'in' then -(value->>'time')::numeric else (value->>'time')::numeric end as time
  from json_array_elements(json_column->'Ui')) as elements
group by 1
order by 1

 element | time_spent 
---------+------------
 TG1     |          2
 TG2     |          8
(2 rows)

递归的具体需求在哪里?