1

Given table of enums

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

How can I select it to get following JSON array of tuples [reaction, count()]?

[
   [laugh, 1], 
   [love, 3], 
   [like, 4], 
   [surprised, 2]
]
5
  • this question maybe help you. Commented Oct 26, 2020 at 2:56
  • @danial it doesn't looks like a regular JSON. Commented Oct 26, 2020 at 4:33
  • @AkhileshMishra it is, why wouldn't it be? yes, no quotes, but array of tuples is valid json Commented Oct 26, 2020 at 12:48
  • I specifically said regular json though it is valid. AFAIK jsob function will not give any output without quotes. Commented Oct 26, 2020 at 13:50
  • Quotes is irrelevant to the question Commented Oct 27, 2020 at 3:36

2 Answers 2

2

You can aggregate the result of a group by query:

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

This would return:

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

Or if you really want the inner key/value pairs as a JSON array:

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

This would return

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

Online example

Sign up to request clarification or add additional context in comments.

Comments

1

You can make use of postgres over partition by and jsonb_build_array function:

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

1 Comment

@a_horse_with_no_name thanks, you are correct, updating answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.