使用多个array_agg和group by更改Postgres选择

时间:2014-07-26 19:25:23

标签: sql postgresql

我在postgres 9.3中编写SQL,几乎完美地运行:

SELECT type_id, to_json(array_agg(row(value, id))) AS json FROM sub_types GROUP BY type_id

结果表显示:

type_id | json
1       | [{"f1":"something", "f2":7}, ...]
2       | [{"f1":"something new", "f2":2}, ...]

我试图这样做结果如下:

type_id | json
1       | [{"value":"something", "id":7}, ...]
2       | [{"value":"something new", "id":2}, ...]

基本思想是编写与此类似的代码(PHP): rows = pdo_call_select

rows = pdo_call_select
foreach (rows as row)
{
  print '<span data-id="row->id">'
  foreach (row->json as otherfields)
    print '<input value="otherfields->value" ...'
    ...

我的表是:

id | type_id | value
1      3         something
2      2         blabla
3      3         something new
4      1         ok
...

2 个答案:

答案 0 :(得分:1)

create table sub_types (
    id int, type_id int, value text
);
insert into sub_types (id, type_id, value) values
(1, 3, 'something'),
(2, 2, 'blabla'),
(3, 3, 'something new'),
(4, 1, 'ok');

select type_id, json_agg(row_to_json(cj)) as json
from
    sub_types st
    cross join lateral
    (select value, id) cj
group by type_id
;
 type_id |                               json                               
---------+------------------------------------------------------------------
       1 | [{"value":"ok","id":4}]
       3 | [{"value":"something","id":1}, {"value":"something new","id":3}]
       2 | [{"value":"blabla","id":2}]

答案 1 :(得分:0)

我为所有json结果创建类型并将行转换为类型。

create table sub_types (
    id int, type_id int, value text
);

create type sub_json_type as (value text, id integer);

insert into sub_types (id, type_id, value) values
(1, 3, 'something'),
(2, 2, 'blabla'),
(3, 3, 'something new'),
(4, 1, 'ok');


SELECT type_id, to_json(array_agg(row(value, id)::sub_json_type)) AS json FROM sub_types GROUP BY type_id;

 type_id |                              json                               
---------+-----------------------------------------------------------------
       1 | [{"value":"ok","id":4}]
       2 | [{"value":"blabla","id":2}]
       3 | [{"value":"something","id":1},{"value":"something new","id":3}]
(3 rows)