首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在postgres列中找到包含jsonb数据的最小值?

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

Stack Overflow用户
提问于 2016-12-20 06:31:38
回答 2查看 394关注 0票数 2

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

代码语言:javascript
运行
复制
{
  "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函数,分离键值对,然后使用最小function.But,仍然不能得到它所属的月份。

如何才能做到这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-20 07:55:35

代码语言:javascript
运行
复制
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
代码语言:javascript
运行
复制
+----------+-------+--------+
| date     | month | amount |
+----------+-------+--------+
| 20161214 | 4     | 642    |
+----------+-------+--------+
票数 1
EN

Stack Overflow用户

发布于 2016-12-20 08:42:43

或者(不加入):

代码语言:javascript
运行
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41236191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档