如何在包含 jsonb 数据的 postgres sql 列中找到最小值?

How to find the minimum value in a postgres sql column which contains jsonb data?

我在 postgres 数据库中有一个 table 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 是金额。

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

我尝试过的:

使用 jsonb_each 函数并分离键值对,然后使用 min function.But 仍然无法获取它所属的月份。

如何实现?

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    |
+----------+-------+--------+

或者(没有连接):

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;