sql子查询将结果插入json

zy1mlcev  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(362)

`我试图将子查询的值返回到一个json\u build\u对象中,子查询返回正确的值,但是当运行full select时,结果是不正确的。值得注意的是,完全选择是视图的左连接。

SELECT r.id, sum(q.total) AS overall_total,
        jsonb_agg(json_build_object('count', q.total, 'type', der.name)) AS totals
        FROM test.table_a p
            JOIN test.table_b r
            ON p.root_id = r.id
                inner join (
                    select r.id,  de.value_id as error_type, count(de.value_id) as total
                    from test.table_c de
                    inner join tests.error dr on de.value_id = dr.id
                    inner join test.table_a p on de.process = p.id
                    inner join test.table_b r on p.root = r.id
                    group by r.id, de.value_id 
            ) q on q.id = r.id
         inner join test.table_c er on er.process = p.id
         inner join tests.error der on er.value_id = der.id
    GROUP BY r.id) er on er.id = rs.id

子查询返回-

由于我试图根据id计算value\u id的出现次数,我相信我得到了正确的信息。
完整的查询结果和所需的输出-

我想返回给定id和json对象数组的总错误数,每个对象中都有类型(value\id文本表示)和该类型中有多少个类型的计数。
目前,查询返回的是错误的total\u total,它似乎在复制数组中的类型。我哪里出错了?

dxpyg8gm

dxpyg8gm1#

我想你不需要 table_b ,请尝试以下查询:

SELECT q.id, SUM(q.total) AS overall_total,
       JSONB_AGG(JSONB_BUILD_OBJECT('count', q.total, 'type', q.name)) AS totals
  FROM (
        SELECT a.root_id AS id, e.name, COUNT(c.value_id) AS total
          FROM table_c c
          JOIN error e
            ON e.id = c.value_id
          JOIN table_a a 
            ON c.process = a.id  
         GROUP BY e.name, a.root_id  ) q
 GROUP BY q.id

演示

相关问题