Postgres json_agg限制

时间:2015-02-08 11:53:09

标签: postgresql aggregate-functions

我在Postgres中使用json_agg就像这样

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

但是我想限制将多少行聚合到JSON中。我想写这样的东西

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

有可能以某种方式吗?

这是完整查询

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"

所以我想为每个部门设立前三名员工。

1 个答案:

答案 0 :(得分:3)

您需要一个子选择,每个leftmentid只返回三行,然后汇总其结果:

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"

请注意,使用带引号的标识符通常不是一个好主意。从长远来看,它比它们的价值更麻烦。