如何将行分组到数组中[PostgreSQL]
表a: 我需要输出最终的表,如下所示:如何将行分组到数组中[PostgreSQL],postgresql,Postgresql,表a: 我需要输出最终的表,如下所示: date_time amount note 2016-03-01 01:00.00.000000 100 "hi" 2016-03-01 02:00.00.000000 5 "hello" 2016-03-01 03:00.00.000000 2 "foo" 2016-04-01 00:00.00.000000 60 "bar"
date_time amount note
2016-03-01 01:00.00.000000 100 "hi"
2016-03-01 02:00.00.000000 5 "hello"
2016-03-01 03:00.00.000000 2 "foo"
2016-04-01 00:00.00.000000 60 "bar"
RowA是第一组中所有行的JSON对象数组:
ProcessedTable
grouped_date_time row total
2016-03-01 RowA 107
2016-04-01 RowB 60
[
{ date_time:2016-03-01 01:00.00.000000, amount:100, note:"hi"},
{ date_time:2016-03-01 02:00.00.000000, amount:5, note:"hello"},
{ date_time:2016-03-01 03:00.00.000000, amount:2, note:"foo"}
]
RowB是第一组中所有行的JSON对象数组:
ProcessedTable
grouped_date_time row total
2016-03-01 RowA 107
2016-04-01 RowB 60
[
{ date_time:2016-03-01 01:00.00.000000, amount:100, note:"hi"},
{ date_time:2016-03-01 02:00.00.000000, amount:5, note:"hello"},
{ date_time:2016-03-01 03:00.00.000000, amount:2, note:"foo"}
]
目前我有这样的疑问
[
{ date_time:2016-04-01 00:00.00.000000, amount:60, note:"bar"}
]
我不知道要将整个JSON对象提取为一列,以及每个组的总金额,应该为数组加什么。以下操作应该有效:
SELECT date_trunc('day', date_time), array_agg(amount)
FROM table_a
GROUP BY date_trunc('day', date_time)
当ROW\u TO_JSON(表a)
将SQL行转换为JSON对象时,JSON\u AGG
将所有对象收集到JSON数组中
输出(使用JSONB\u PRETTY
):
编辑:通过删除行到行JSON
,可以进一步简化查询:
date_trunc | row | total
---------------------+--------------------------------------------+-------
2016-03-01 00:00:00 | [ +| 107
| { +|
| "note": "hi", +|
| "amount": 100, +|
| "date_time": "2016-03-01T01:00:00"+|
| }, +|
| { +|
| "note": "hello", +|
| "amount": 5, +|
| "date_time": "2016-03-01T02:00:00"+|
| }, +|
| { +|
| "note": "foo", +|
| "amount": 2, +|
| "date_time": "2016-03-01T03:00:00"+|
| } +|
| ] |
2016-04-01 00:00:00 | [ +| 60
| { +|
| "note": "bar", +|
| "amount": 60, +|
| "date_time": "2016-04-01T00:00:00"+|
| } +|
| ] |
您可以在进入
row\u to_json
之前选择整行,使用cte
和groupby
SELECT DATE_TRUNC('day', date_time), JSON_AGG(t) AS row, SUM(amount) AS total
FROM table_a t GROUP BY DATE_TRUNC('day', date_time);
哇。您正在将
表a
传递给函数。我必须做复杂的体操才能单独划船。这太好了@奎师那:不,我没有把表格放到行到JSON
<代码>ta是当前行的参考。您还可以使用表别名或以逗号分隔的列名列表。了解的越多!在某种意义上,内置了这样的功能。我的第一次尝试是将*
传递到行\u到\u json
,但没有成功。