PostgreSQL:需要获取Json格式的值

时间:2018-11-01 15:51:00

标签: json postgresql

我想获取此JSON值(获得每个用户crm_call_log的总数)。

{series: [{'user_id': 1, 'count': 2}, {'user_id': 3, 'count': 1}], xaxis: ['User1', 'User3']}

我有两个桌子,

res_users

| id |  name |
|----|-------|
|  1 | User1 |
|  2 | User2 |
|  3 | User3 |

crm_call_log

| id | user_id |                            name |
|----|---------|---------------------------------|
|  1 |       1 |               Did not connected |
|  2 |       1 |                  Call connected |
|  3 |       3 | Call connected, but doesn't won |

我尝试的是

select 
    array_to_json(array_agg(B)) 
from (
    select 
        array_to_json(array_agg(A)) as series
    from (
        select 
            user_id as id,
            count(id) as value
        from crm_call_log
        group by user_id
        order by 2 desc
    ) as A
) as B

所以最后我得到了这个输出

[{"series":[{"id":1,"value":2},{"id":3,"value":1}]}]

所以在这方面有人帮助我。

1 个答案:

答案 0 :(得分:1)

demo:db<>fiddle

SELECT 
    row_to_json(s)                                     -- 5
FROM (
    SELECT 
        json_agg(                                      -- 4
            json_build_object('user_id', user_id, 'count', count) -- 3
        ) as series,
        json_agg(rs.name) as xaxis                     -- 4
    FROM (
        SELECT ccl.user_id, COUNT(*)                   -- 1 
        FROM crm_call_log ccl 
        GROUP BY ccl.user_id
    )s
    JOIN res_users rs                                  -- 2
    ON s.user_id = rs.id
)s
  1. 将表user_id中的crm_call_log s分组以进行计数
  2. 加入res_users获得name的{​​{1}}
  3. user_id创建像json_build_object
  4. 这样的json元素
  5. {'user_id': 1, 'count': 2}将(3)中的json对象和用户json_agg s聚合到json数组中
  6. name使用列名作为键从子查询中创建一个json对象。

Postgres JSON aggregatesPostgres JSON functions