【问题标题】:Compare multiple date fields in JSON and use them in where clause比较 JSON 中的多个日期字段并在 where 子句中使用它们
【发布时间】:2021-12-21 01:45:33
【问题描述】:

所以我的 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
}

earliest 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

有人知道怎么做吗?

【问题讨论】:

    标签: arrays json postgresql filter where-clause


    【解决方案1】:

    如果您的表具有唯一值或具有 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
    

    【讨论】:

    • 奇怪的是我实现了你的代码,但我在日期列中到处都是 null ..
    • 这里是sample query,但是在我看来,你的记录太多了,我改了查询,用窗口函数写了
    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2021-10-09
    • 2017-11-24
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多