问题描述:
查询本月入库的材料单价时,同时查询去年最后一次入库的单价做为参考价格.请教大家怎么写下面的查询速度能快些,
select v1.mtrl_id,v1.price,v2.last_price from
(select mtrl_id,price from table1 where mnth='2009-01')v1 left join
(select mtrl_id,price as last_price from table1 where year='2008' and
           date=(select max(date) from table1 where year='2008'))v2 on v2.mtrl_id=v1.mtrl_id现在这个查询速度极慢,我用存储过程来处理,怎么处理都行,建临时表或者其他办法都行谢谢各位了!

解决方案 »

  1.   


    select mtrl_id,price,last_price from
    TABLE1 A, (select max(date) DATE from table1 where year='2008')B
    WHERE A.DATE=B.DATE
    A.MNTH='2009-01'
      

  2.   

    WHERE后面漏了个AND~LZ自己加上
      

  3.   

    select v1.mtrl_id,v1.price,v2.last_price 
    from (select mtrl_id,price from table1 where mnth='2009-01')v1 
    left join 
    (select * 
    from (select T.*,rownumber() over(partition by mtrl_id,date order by date desc) rn from table1 T where year='2008')A
    where rn=1
    )v2
    on v2.mtrl_id=v1.mtrl_id 
      

  4.   

    上面的rownumber()改为row_number()
      

  5.   


    select v1.mtrl_id, v1.price, v2.price last_price
      from (select mtrl_id, price from table1 where mnth = '2009-01') v1,
           (select mtrl_id, price
              from (select mtrl_id,
                           date,
                           price,
                           rank() over(partition by mtrl_id, date order by date desc) rk
                      from table1
                     where year = '2008') A
             where rk = 1) v2
     where v1.mtrl_id = v2.mtrl_id(+)