Select 作为元组数组 postgresql

Select as array of tuples postgresql

给定 table 个枚举

|id |reaction |
|-- |-------- |
|1  |laugh    |
|2  |love     |
|3  |love     |
|4  |like     |
|5  |like     |
|6  |surprised|
|7  |like     |
|8  |love     |
|9  |like     |
|10 |surprised|

我怎样才能select它得到以下JSON元组数组[reaction, count()]

[
   [laugh, 1], 
   [love, 3], 
   [like, 4], 
   [surprised, 2]
]

您可以使用 postgres over partition by 和 jsonb_build_array 函数:

SELECT
    jsonb_build_array(json_reactions.reaction, count)
FROM
    (
    SELECT
        DISTINCT reaction, count(*) OVER (PARTITION BY reaction)
    FROM
        reactions r ) AS json_reactions ;

您可以通过查询汇总一组结果:

select jsonb_agg(jsonb_build_object(reaction, count))
from (
  select reaction, count(*)
  from the_table
  group by reaction
) t;  

这会 return:

[
  {"surprised": 2}, 
  {"like": 4}, 
  {"laugh": 1}, 
  {"love": 3}
]

或者如果你真的想要内部 key/value 对作为 JSON 数组:

select jsonb_agg(array[reaction, "count"])
from (
  select reaction, count(*)::text as "count"
  from the_table
  group by reaction
) t;  

这会 return

[
  ["surprised","2"],
  ["like","4"],
  ["laugh","1"],
  ["love","3"]
]

Online example