根据日期和支票加入表格

时间:2017-06-26 11:34:21

标签: sql postgresql

我在PostgreSQL中有两个表:

Demans_for_parts

   demandid partid  demanddate        quantity 
    40       125     01.01.17          10
    41       125     05.01.17          30
    42       123     20.06.17          10

Orders_for_parts

  orderid  partid orderdate        quantity 
   1        125     07.01.17     15
   54       125     10.06.17     25
   14       122     05.01.17     30

基本上Demans_for_parts说买什么,Orders_for_parts说我们买了什么。我们可以购买未在Demans_for_parts上列出的零件。

我需要一份报告,向我展示Demans_for_parts中的所有部分以及自Orders_for_parts中最近匹配行以来已过去的几周。注意数量字段在这里无关紧要,

预期结果是(如果每个部分多行显示oldes):

partid   demanddate        weeks_since_recent_order
125     01.01.17                  2   (last order is on 10.06.17)
123     20.06.17                Unhandled

2 个答案:

答案 0 :(得分:1)

我认为棘手的部分是每桌获得一行。但使用distinct on很容易。然后你需要计算月份。您可以将age()用于此目的:

select dp.partid, dp.date,
       (extract(year from age(dp.date, op.date))*12 +
        extract(month from age(dp.date, op.date))
       ) as months
from (select distinct on (dp.partid) dp.*
      from demans_for_parts dp
      order by dp.partid, dp.date desc
     ) dp left join
     (select distinct on (op.partid) op.*
      from Orders_for_parts op
      order by op.partid, op.date desc
     ) op
     on dp.partid = op.partid;

答案 1 :(得分:0)

是什么样的?

with o as (
  select distinct partid, max(orderdate) over (partition by partid)
  from Orders_for_parts
)
, p as (
  select distinct partid, min(demanddate) over (partition by partid)
  from Demans_for_parts
)
select p.partid, min as demanddate, date_part('day',o.max - p.min)/7
from p
left outer join o on (p.partid = o.partid)
;