小编lra*_*rai的帖子

如何在 JSON_AGG 中使用 ORDER BY 和 LIMIT

我有一个返回所需输出的查询。

SELECT 
    shop,
    JSON_AGG(item_history.* ORDER BY created_date DESC) as data
FROM item_history
GROUP BY
    shop;
Run Code Online (Sandbox Code Playgroud)

结果:

[
  {
    "shop": "shop1",
    "data": [
      {
        "id": 226,
        "price": "0",
        "shop": "shop1.com",
        "country": "UK",
        "item": "item1",
        "created_date": "2021-06-07T08:48:42.338201",
      },
      {
        "id": 224,
        "price": "0",
        "shop": "shop1.com",
        "country": "UK",
        "item": "item 1",
        "created_date": "2021-06-07T07:53:25.030621",
      },
      ...
  },
  {
    "shop": "shop2",
    "data": [
      {
        "id": 225,
        "price": "0",
        "shop": "shop2.com",
        "country": "DE",
        "item": "Item 2",
        "created_date": "2021-06-07T08:48:36.443849",
      },
      ...
]
Run Code Online (Sandbox Code Playgroud)

这正是我想要的输出,但问题是它获取data数组下的所有项目,最好限制该数组。我尝试添加LIMIT

SELECT …
Run Code Online (Sandbox Code Playgroud)

postgresql order-by sorting limits group-by

3
推荐指数
1
解决办法
8548
查看次数

标签 统计

group-by ×1

limits ×1

order-by ×1

postgresql ×1

sorting ×1