【发布时间】: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