Skip to content
Advertisement

how to get json result to fixed number by grouping in postgresql?

I want to get expected results to one query execution. the “where” clause should one value. so I can’t use this query as sub-query of main-query.

could you tell me how to do it?

Sample sql query:

Expected results:

results
[{“id”:1,”name”:”hello”},{“id”:4,”name”:”good”},{“id”:7,”name”:”world”}, {“id”:9,”name”:”happy”}]
[{“id”:10,”name”:”funny”},{“id”:12,”name”:”stack”},{“id”:15,”name”:”queue”},{“id”:18,”name”:”map”}]
[{“id”:19,”name”:”list”},{“id”:23,”name”:”code”}]

Advertisement

Answer

demo: db<>fiddle

  1. Convert your records into JSON objects
  2. Create a row count using the row_number() window function
  3. Create groups of 4 by using integer division
  4. Aggregate these groups into a JSON array
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement