题库信息参考:https://bbs.csdn.net/topics/60035400

库存信息:

现有一表记录产品进出库
product_id(产品代码)  inoutdate(出入库日期)     qty(数量)
001                     20200701                 10
001                     20200703                -8
001                     20200704                -1
001                     20200705                 5
001                     20200707                -6
其中数量为正表示入库,数量为负表示出库,现要计算任意日期时库存产品的库存天数。系统默认先进先出。
比如当前日期为+1天进行查询

    查询20200702日库龄,则为10个、库龄为1天
    查询20200703日库龄,则为2个、库龄为2天
    查询20200704日库龄,则为1个、库龄为3天
    查询20200705日库龄,则为1个、库龄为4天和5个、库龄为0天
    查询20200706日库龄,则为1个、库龄为5天和5个、库龄为1天
    查询20200707日库龄,则为0个、库龄为0

-- 20200719 日期作为变量传入

with p_dw as
 (select '001' pid, '20200701' date_id, 10 qty
    from dual
  union all
  select '001' pid, '20200703' date_id, -8 qty
    from dual
  union all
  select '001' pid, '20200704' date_id, -1 qty
    from dual
  union all
  select '001' pid, '20200705' date_id, 5 qty --3 
    from dual
  union all
  select '001' pid, '20200707' date_id, -3 qty
    from dual
  union all
  select '001' pid, '20200708' date_id, 9 qty --9 
    from dual
  union all
  select '001' pid, '20200709' date_id, 7 qty --7 
    from dual
  union all
  select '001' pid, '20200710' date_id, 7 qty --7 
    from dual)
select pid,
       --qty,
       date_id,
       days,
       current_store_nums cnt_qty,
       --nvl(lag(current_store_nums) over (partition by pid order by date_id),0) LAST_ROWS,
       current_store_nums -
       nvl(lag(current_store_nums) over(partition by pid order by date_id),
           0) current_store_row__qty
  from (select pid,
               qty,
               date_id,
               to_date('20200719', 'yyyymmdd') -
               to_date(date_id, 'yyyymmdd') days,
               SUM(case
                      when qty < 0 then
                       qty
                      else
                       0
                    end) OVER(PARTITION BY PID) + SUM(case
                 when qty > 0 then
                  qty
                 else
                  0
               end) OVER(PARTITION BY PID ORDER BY DATE_ID) current_store_nums
          from p_dw
         where date_id <= '20200719')
 WHERE current_store_nums > 0
   AND QTY > 0

 

 

 

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐