当postgresql

时间:2017-05-09 15:41:09

标签: sql postgresql

我有一个库存数量表,按部件号,地点#和日期。如果当天发生了变化,表中只有一条记录。例如:

part  |loc   |date      |qtyonhand
------+------+----------+---------
10544 | 3012 | 20161116 | 68
10544 | 3012 | 20170403 | 43  <----- 
10544 | 3012 | 20170413 | 33  <-----

对于每个part / loc键,我需要计算手头上的平均数量 过去3个月。自2017年5月起,我需要计算2月,3月和2月。 2017年4月,其中包括显示的两个记录。但我不能只取43和33的平均值除以2.对于这部分/ loc,计算应该是这样的:

20170201 inventory was 68
20170202 inventory was 68
...for each day
20170402 inventory was 68
20170403 inventory was 43
20170404 inventory was 43
...
20170413 inventory was 33
...
20170430 inventory was 33

我将每天的库存总和除以2月1日到4月30日之间的天数。

我尝试使用lag()计算日期之间的差异,然后将其乘以库存水平,但我无法弄清楚如何使用之前的更改记录数量从2月1日获取值下一个变更记录。

非常感谢任何提示或方向。

1 个答案:

答案 0 :(得分:0)

您可以使用lag()和句点上的逻辑来执行此操作。如果我有算术权:

select part, loc, 
       sum(days_in_period * prev_quantity)/ sum(days_in_period) as average
from (select t.*,
             greatest(least(date, period_end) - greatest(prev_date, period_start) + 1, 0) as days_in_period
      from (select t.*,
                   lag(date) over (partition by part, loc order by date) as prev_date,
                   lag(qtyonhand) over (partition by part, loc order by date) as prev_qtyonhand
            from t
           ) t cross join
           (select '2017-02-01'::date as period_start, '2017-04-30'::date as period_end,
     ) t
group by part, loc;
相关问题