在JSONB列的特定日期之前的最后给定值

时间:2017-09-01 08:34:46

标签: arrays postgresql jsonb

我希望从具有on id和2 JSONB-column的BD获取特定日期(在本例中为2015-09-30)之前的最后一个给定值,如下所示:

1, 
[
    {"value": 4290, "time": "2014-05-15T05:31:45.077483Z"}, 
    {"value": 3490, "time": "2014-09-02T04:32:32.094733Z"}, 
    {"value": 3690, "time": "2015-01-16T04:32:28.679849Z"}, etc...
    ],
[
    {"stock_status": "instock", "time": "2014-06-15T05:31:45.077483Z"}, 
    {"stock_status": "outofstock", "time": "2014-07-02T04:32:32.094733Z"}, 
    {"stock_status": "instock", "time": "2015-01-26T04:32:28.679849Z"}, etc...
    ],
2, 
[
    {"value": 4598, "time": "2013-05-15T05:31:45.077483Z"}, 
    {"value": 3456, "time": "2014-04-02T04:32:32.094733Z"}, 
    {"value": 4354, "time": "2015-06-16T04:32:28.679849Z"}, etc...
    ]
[
    {"stock_status": "outofstock", "time": "2014-06-15T05:31:45.077483Z"}, 
    {"stock_status": "instock", "time": "2014-07-02T04:32:32.094733Z"}, 
    {"stock_status": "outofstock", "time": "2015-01-26T04:32:28.679849Z"}, etc...
    ]

我所追求的查询应该给出;

  • 编号
  • 日期之前的第一个值
  • 如果日期之前的第一个stock_status =“instock”

但是我无法获得正确的时间戳,如果任何stock_status是“instock”,它会在日期之前返回所有值。我的查询:

SELECT sph.id, elem1->>'value', elem1->>'time'
    FROM table as sph,
    jsonb_array_elements(sph.value_column) as array1(elem1),
    jsonb_array_elements(sph.stock_status_coulmn) as array2(elem2)

        where elem1 = (select elem1
    where elem1->> 'time'  <= '2015-09-30' and elem2->> 'time'  <= '2015-09-30' and elem2->>'stock_status' = 'instock'
order by elem1->>'time' desc
limit 1);

我希望这只能从上面的db-exemple返回一个结果,即id为1的结果。

任何提示?这让我疯狂了几天......

1 个答案:

答案 0 :(得分:0)

最后我解决了这个问题:

SELECT DISTINCT ON (sph.id) sph.id, elem1->>'value' as value, elem1->>'time' as time, elem2->>'stock_status' as stock_status
    FROM table as sph
    join table2 as sp on sph.id = sp.id,
    jsonb_array_elements(sph.value_column) as array1(elem1),
    jsonb_array_elements(sph. stock_status_coulmn) as array2(elem2)

    WHERE elem1#>>'{time}' <= '2015-09-30' and elem2#>>'{time}' <= '2015-09-30'
ORDER BY sph.id, elem1#>>'{time}' DESC, elem2#>>'{time}' DESC;

然后我将我的代码(elixir)中的废品行和错误的行分类,而不是确定它是最好的方法,但无论如何都适合我。 :)