如何在Postgres中排序我的Json数组

时间:2017-11-03 04:13:36

标签: sql arrays json postgresql

我有一个已排序的Json数组:

_bb = 

[
  {
    "so": "1",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "2",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "1",
    "mdl": "FlashSale",
    "pos": "Bottom"
  }
]

我正在使用这个公用表表达式来分组和排列'pos'。

with j(_bb) as (values(_con))
, ord(o,v) as (values(1,'Top'),(2,'Left'),(3,'Content'),(4,'Right'),(5,'Bottom'))
, un as (select *,jsonb_array_elements(_con) i from j)
select jsonb_agg(i order by o) from un
join ord on v=i->>'pos' into _test;

我想要实现的是在根据'pos'值分组和排列订单之后。我还希望根据他们的'so'价值来安排他们。 _test返回基于'pos'的排序值。

这就是我想要实现的目标:

[
  {
    "so": "1",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "2",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "1",
    "mdl": "FlashSale",
    "pos": "Bottom"
  },
   {
    "so": "2",
    "mdl": "FlashSale",
    "pos": "Bottom"
  }
]

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我只需要按i->>'so'

添加另一个订单
   with j(_bb) as (values([
  {
    "so": "1",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "2",
    "mdl": "Testing",
    "pos": "Top"
  },
  {
    "so": "1",
    "mdl": "FlashSale",
    "pos": "Bottom"
  },
   {
    "so": "2",
    "mdl": "FlashSale",
    "pos": "Bottom"
  }
]::jsob))
    , ord(o,v) as (values(1,'Top'),(2,'Left'),(3,'Content'),(4,'Right'),(5,'Bottom'))
    , un as (select *,jsonb_array_elements(_bb) i from j)
    select jsonb_agg(i order by o,i->>'so') from un
    join ord on v=i->>'pos';