string_agg 函数中的 Postgresql 限制

Postgresql limit in string_agg function

我有如下查询:

SELECT string_agg(sn::text, ','), product_id
  FROM irmsapp_serializedinventory
  group by product_id;

结果是聚合的 sno 字段和产品。我想知道我们是否可以将串联限制为 5 个并将其余的留给 sno 字段。目前我的 sno 字段是一个大列表,我想将它缩减为 5 个元素的列表(排序顺序中的前 5 个元素)。

关系数据库中的行是而不是"sorted"。您需要有一些可以对结果进行排序的列,然后您才能指定哪些行是 "first five".

假设你有,例如定义 "first five" 的 created_at 列,您可以这样做:

select string_agg(sno::text, ','), product_id
from (
   select product_Id, sno,
          row_number() over (partition by product_id order by created_at desc) as rn
   from irmsapp_serializedinventory
) t
where rn <= 5
group by product_id;

这会为每个产品选择 5 行 。如果您只想要 5 行而不考虑 product_id,那么只需删除 window 函数中的 partition by product_id

order by created_at desc 定义排序顺序以及聚合中使用的五行。