我在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函数。但是我仍然无法得到它所属的月份。
如何实现这一目标?
答案 0 :(得分: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 :(得分:0)
或者(没有连接):
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;