SQL - 从两行到新的两行的值

时间:2017-11-21 12:41:09

标签: sql oracle

我有一个查询,它会在工作日提供一定数量的项目。在周末和假日,数量值和项目值为空。 我希望在空旷的日子里,最后已知的数量和项目。 我的查询是这样的:

`select a.dt,b.zaliha as quantity,b.artikal as item
from
(select to_date('01-01-2017', 'DD-MM-YYYY') + rownum -1 dt 
from dual 
connect by level <= to_date(sysdate) - to_date('01-01-2017', 'DD-MM-YYYY') + 1
order by 1)a
LEFT OUTER JOIN
(select kolicina,sum(kolicina)over(partition by artikal order by datum_do) as zaliha,datum_do,artikal
from
(select sum(vv.kolicinaulaz-vv.kolicinaizlaz)kolicina,vz.datum as   datum_do,vv.artikal
from vlpzaglavlja vz, vlpvarijante vv
where vz.id=vv.vlpzaglavlje
and vz.orgjed='01006'
and vv.skladiste='01006'
and vv.artikal in (3069,6402)
group by vz.datum,vv.artikal
order by vv.artikal,vz.datum asc)
order by artikal,datum_do asc)b
on a.dt=b.datum_do
where a.dt between to_date('12102017','ddmmyyyy') and     to_date('16102017','ddmmyyyy')
order by a.dt`

我的输出是这样的:

Current Output

我想要这个:

Expected Output

1 个答案:

答案 0 :(得分:0)

简而言之,如果数量为空,请使用lag(... ignore nulls)coalescenvl

select dt, item, 
       nvl(quantity, lag(quantity ignore nulls) over (partition by item order by dt))
  from t
  order by dt, item

这是完整的查询,我无法测试它,但它类似于:

with t as (
  select a.dt, b.zaliha as quantity, b.artikal as item
    from ( 
      select date '2017-10-10' + rownum - 1 dt 
        from dual 
        connect by date '2017-10-10' + rownum - 1 <= date '2017-10-16' ) a
      left join (
        select kolicina, datum_do, artikal,
               sum(kolicina) over(partition by artikal order by datum_do) as zaliha
          from (
            select sum(vv.kolicinaulaz-vv.kolicinaizlaz) kolicina, 
                   vz.datum as datum_do, vv.artikal
              from vlpzaglavlja vz 
              join vlpvarijante vv on vz.id = vv.vlpzaglavlje
              where vz.orgjed = '01006' and vv.skladiste='01006' 
                and vv.artikal in (3069,6402)
              group by vz.datum, vv.artikal)) b
        on a.dt = b.datum_do)
select * 
  from (
    select dt, item, 
           nvl(quantity, lag(quantity ignore nulls) 
                         over (partition by item order by dt)) qty
      from t)
  where dt >= date '2017-10-12'
  order by dt, item

您的查询中有几个问题,主要和次要问题:

  • 在日期生成器(子查询a)中,您选择从长期,1月到9月的日期,然后加入主表并汇总数据,然后仅选择小部分。为什么不首先过滤日期?,
  • to_date(sysdate)sysdate已经是日期,
  • 使用ansi join,
  • 不要在子查询中使用order by,它没有影响,只有最后的排序很重要,
  • 在定义日期时使用日期文字,它更具可读性。