首页 > 解决方案 > 比较 JSON 中的多个日期字段并在 where 子句中使用它们

问题描述

所以我的 Postgres 10.8 (json_array_elements not possible) DB中有一个文本字段。它有一个像这样的json结构。

{
  "code_cd": "02",
  "tax_cd": null,
  "earliest_exit_date": [
    {
      "date": "2023-03-31",
      "_destroy": ""
    },
    {
      "date": "2021-11-01",
      "_destroy": ""
    },
    {
      "date": "2021-12-21",
      "_destroy": ""
    }
  ],
  "enter_date": null,
  "leave_date": null
}

最早的 exit_date 也可以为空,如下所示:

{
  "code_cd": "02",
  "tax_cd": null,
  "earliest_exit_date":[],
  "enter_date": null,
  "leave_date": null
}

现在我想找回最早的退出日期,日期在 current_date 之后,并且是最接近 current_date 的日期。从 early_exit_date 的示例中,输出必须是:2021-12-21

任何人都知道如何做到这一点?

标签: arraysjsonpostgresqlfilterwhere-clause

解决方案


如果您的表具有唯一值或具有 id,您可以使用以下查询:

示例表和数据结构:dbfiddle

select distinct
  id,
  min("date") filter (where "date" > current_date) over (partition by id)
from 
  test t
  cross join jsonb_to_recordset(t.data::jsonb -> 'earliest_exit_date') as e("date" date)
order by id

推荐阅读