4

I'm using json_agg in Postgres like this

json_agg((e."name",e."someOtherColum",e."createdAt") order by e."createdAt" DESC )

But I want to limit how many rows will be aggregated into JSON. I want to write something like this

json_agg((e."name",e."someOtherColum",e."createdAt") order by e."createdAt" DESC  LIMIT 3)

Is it possible in some way?

This is full query

SELECT e."departmentId",
json_agg((e."name",e."someOtherColum",e."createdAt") order by e."createdAt" DESC ) as "employeeJSON" 
FROM "Employee" e 
GROUP BY e."departmentId"

So I want to achieve department with first three employees for each department.

1 Answer 1

6

You need a sub-select that returns only three rows per departmentid and then aggregate the result of that:

select "departmentId", 
       json_agg(("name","someOtherColum","createdAt") order by "createdAt" DESC) as "employeeJSON"
FROM (
  SELECT "departmentId",
         "name"
         "someOtherColum",
         "createdAt", 
         row_number() over (partition by "departmentId" order by "createdAt") as rn
  FROM "Employee"
) t
WHERE rn <= 3
GROUP BY "departmentId"

Note that using quoted identifiers is in general not such a good idea. In the long run it's more trouble than they are worth it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.