querying over multiple data from function in PostgreSQL

时间:2017-04-02 11:57:50

标签: sql postgresql

I have a function which gives stock levels:

select * from stocklevel(ID)

This function gives stock leverl per ID. For example:

select * from stocklevel(23)

Result is:

   ID  datelevel  stocklevel
   23   01.01.17   15
   23   02.01.17   18
   23   05.01.17   20

This is the stock level for ID=23.

Not all dates appear, it depends on many things.

I want to use this function to get the stock levels for all parts from my system

basically something like this:

select *,(select stocklevel from stocklevel(parts.partid) where datelevel = ??? )
from parts

OR:

  select *
  from parts
  left join ( select stocklevel from stocklevel(parts.partid) where datelevel = ??? ) using (ID)

Now, the issue is with the WHERE condition I want to specific a specific date like '04.01.17' but if the date does not exist i want it to take the date before that so:

for the ID=23 and date '04.01.17' it should show 18,'02.01.17' .

for the ID=23 and date '15.01.13' it should show nothing.

for the ID=23 and date '05.01.17' it should show 20,'05.01.17' .

How can I do that?

2 个答案:

答案 0 :(得分:1)

首先,我会使用lateral加入:

select *
from parts p left join lateral
     stocklevel(p.partid);

然后问题是您想要在给定日期之前或之后的最新级别。您可以使用distinct on

执行此操作
select distinct on (p.id) . . .
from parts p left join lateral
     stocklevel(p.partid)
where datelevel <= ?
order by p.id, datelevel desc;

注意:这不会返回在给定日期之前没有日期的部分。你可能想要:

where datelevel is null or datelevel <= ?

答案 1 :(得分:0)

select *
  from parts
  left join ( select stocklevel 
      from stocklevel(parts.partid) 
      where datelevel = (select max(datelevel) 
            from stocklevel(parts.partid) sl2 
            where sl2.datelevel <= '04.01.17') using(ID) ) using (ID)

未经测试...