【问题标题】:Get sql query result as json获取 sql 查询结果为 json
【发布时间】:2015-06-09 09:58:33
【问题描述】:

我有一个包含两列 A 和 B 的表测试,并从中创建 table1 和 table2。

 test          table1              table2
A   B         A  count(A)       B  count(B)   A
95  1         95   7            1     3       95
 5  11         5   2            11    2        5
95  1                           9     4       95
95  9
95  1
95  9
 5  11
95  9
95  9

如何得到如下结果:

{"node": [   
    {"child": [
              {"value": 3,
               "name": "1"},
              {"value": 4,
               "name": "9"}],
       "value": 7,
       "name": "95"},
   {"child": [
             {"value": 2,
              "name": "11"}],
      "value": 2,
      "name": "5"}],
 "name": "test",
 "value": 9}

首先,我按 A 列分组并计算组 name="95", value=7 和 name="5", value=2。对于每个组,我还计算 B 列。有很多 json 函数,但直到现在我不知道如何得到上面的结果。

查询应该类似于:

select row_to_json(t) from ( select * , ( select array_to_json(array_agg(row_to_json(u))) from ( select * from table1 where table1.a=table2.a ) as u ) from table2 ) as t;

【问题讨论】:

  • 根据您的表格,您的 json 确实没有任何意义,您能否详细解释一下您希望如何获取名称和值?
  • 我编辑了我的开始帖子,我所做的是我计算 A 并希望将“95”的数量保存在变量 value=7 中。然后我将两组(“95”和“5”)都计算在 B 上。
  • sqlfiddle.com/#!9/568307/3 这是您从数据库中获取数据的方式,但不知道如何在不使用应用层的情况下将其放入该格式
  • 我也知道如何计算 A 列和 B 列。我猜我需要的 json 格式是可能的,类似于 (stackoverflow.com/questions/21137237/…)

标签: sql postgresql


【解决方案1】:

您可以使用 plpgsql 函数生成正确的 json。这不是很困难,虽然有时有点乏味。检查这个(将tt重命名为实际表名):

create or replace function test_to_json()
returns json language plpgsql
as $$
declare
    rec1 record;
    rec2 record;
    res text;
begin
    res = '{"node": [';
    for rec1 in
        select a, count(b) ct
        from tt
        group by 1
    loop
        res = format('%s{"child": [', res);
        for rec2 in
            select a, b, count(b) ct
            from tt
            where a = rec1.a
            group by 1,2
        loop
            res = res || format('{"value": %s, "name": %s},', rec2.ct, rec2.b);
        end loop;
        res = rtrim(res, ',');
        res = format('%s],"value": %s, "name": %s},', res, rec1.ct, rec1.a);
    end loop;
    res = rtrim(res, ',');
    res = format('%s], "value": %s}', res, (select count(b) from tt));
    return res:: json;
end $$;

select test_to_json();

【讨论】:

【解决方案2】:

丑陋但可以工作且没有 plpgsql:

select json_build_object('node', json_agg(q3), 'name', 'test', 'value', (select count(1) from test))
from
(select json_agg(q2) from 
    (select a as name, sum(value) as value, json_agg(json_build_object('name', q1.name, 'value', q1.value)) as child 
    from
        (select a, b as name, count(1) as value from test group by 1, 2) as q1
    group by 1) as q2
) as q3;

【讨论】:

  • 哪种方式更容易?恭喜:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 2010-11-24
  • 2021-08-22
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多