【问题标题】:How to find the minimum value in a postgres sql column which contains jsonb data?如何在包含 jsonb 数据的 postgres sql 列中找到最小值?
【发布时间】:2016-12-20 06:31:38
【问题描述】:

我在 postgres 数据库中有一个表 t。它有一列data,其中包含以下格式的jsonb数据(对于每条记录)-

{
  "20161214": {"4": ["3-14", "5-16", "642"], "9": ["3-10", "5-10", "664"] },
  "20161217": {"3": ["3-14", "5-16", "643"], "7": ["3-10", "5-10", "661"] } 
}

20161214 是日期,"4" 是月份,642 是金额。

我需要找到表中每条记录的最小金额以及该金额所属的月份。

我尝试过的:

使用jsonb_each函数,分离键值对,然后使用min函数。但是我仍然无法得到它所属的月份。

如何做到这一点?

【问题讨论】:

  • 数量总是是数组中的第三个元素吗?
  • 我注意到确切的要求是什么,所以我给你写了 2 个解决方案,请看看它们是否适合。
  • 是的,金额始终是第三个元素。

标签: sql postgresql jsonb


【解决方案1】:
select  j2.date
       ,j2.month
       ,j2.amount

from    t 

        left join lateral  

           (select      j1.date
                       ,j2.month
                       ,(j2.value->>2)::numeric  as amount

            from        jsonb_each (t.data) j1 (date,value) 

                        left join lateral jsonb_each (j1.value) j2 (month,value)
                        on true

            order by    amount

            limit       1   
            ) j2

        on true

+----------+-------+--------+
| date     | month | amount |
+----------+-------+--------+
| 20161214 | 4     | 642    |
+----------+-------+--------+

【讨论】:

  • 这正是我所需要的,非常感谢嘟嘟!
  • 你能解释一下这个查询吗?为什么使用某些东西,例如限制 1
  • 无限制地执行查询
  • 嗨 Dudu,我们如何更改上述查询以获取每个日期的最小值,例如日期 20161214、642 和日期 20161217、643?
【解决方案2】:

或者(没有连接):

select
    min(case when amount = min_amount then month end) as month,
    min_amount as amout
from (
    select
        key as month,
        (select min((value->>2)::int) from jsonb_each(value)) as amount,
        min((select min((value->>2)::int) from jsonb_each(value))) over(partition by rnum) as min_amount,
        rnum
    from (
        select
            (jsonb_each(data)).*,
            row_number() over() as rnum
        from t
    ) t
) t
 group by
     rnum, min_amount;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 2020-10-14
    • 2020-09-16
    • 2020-02-20
    • 2021-08-09
    • 2018-03-04
    • 2019-01-23
    • 2016-08-29
    相关资源
    最近更新 更多