我想获取此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}]}]
所以在这方面有人帮助我。
答案 0 :(得分:1)
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
user_id
中的crm_call_log
s分组以进行计数res_users
获得name
的{{1}} user_id
创建像json_build_object
{'user_id': 1, 'count': 2}
将(3)中的json对象和用户json_agg
s聚合到json数组中name
使用列名作为键从子查询中创建一个json对象。