如何在标识符中按标识符分组并创建JSON对象数组?

时间:2019-06-28 20:32:14

标签: postgresql postgresql-9.5

我有一个交易表,我需要按customerId分组并在数组中创建聚合的JSON记录。

customerId|transactionVal|day
      1234|             2|2019-01-01
      1234|             3|2019-01-04
        14|             1|2019-01-01

我想要做的是返回如下内容:

customerId|transactions
      1234|[{'transactionVal': 2, 'day': '2019-01-01'}, {'transactionVal': 3, 'day': '2019-01-04'}]
        14|[{'transactionVal': 1, 'day': '2019-01-01'}]

稍后,我将需要遍历数组中的每个事务以计算transactionVal中的%变化。

我搜索了一段时间,但似乎找不到解决该问题的方法,因为该表很大> 7,000万行。

谢谢!

1 个答案:

答案 0 :(得分:1)

应该可以像这样使用array_aggjson_build_object

ok=# select customer_id, 
     array_agg(json_build_object('thing', thing, 'time', time)) 
     from test group by customer_id;

 customer_id |                                             array_agg                                             
-------------+---------------------------------------------------------------------------------------------------
           2 | {"{\"thing\" : 1, \"time\" : 1}"}
           1 | {"{\"thing\" : 1, \"time\" : 1}",
                "{\"thing\" : 2, \"time\" : 2}",
                "{\"thing\" : 3, \"time\" : 3}"}
(2 rows)

ok=# select * from test;
 customer_id | thing | time 
-------------+-------+------
           1 |     1 |    1
           2 |     1 |    1
           1 |     2 |    2
           1 |     3 |    3
(4 rows)

ok=#