一个价格表Price :表结构和字段如下:货品            价格类型             生效日期           价格 
A                 批发价             2010/01/05          10
A                 批发价             2009/05/30          8
A                 零售价             2011/05/01          15
A                 零售价             2005/04/01          15
A                 零售价             2010/01/15          20
B                 批发价             2011/02/05          10
B                 批发价             2010/12/05          10
B                 批发价             2009/05/30          8
B                 零售价             2005/04/01          15
B                 零售价             2010/01/15          20要求的是最新(生效日期最后)的批发价和零售价和今天用的批发价和零售价SQL如何写呢?

解决方案 »

  1.   

    select * from price t
    where not exists(select 1 from price b where t.货品=b.货品 and t.价格类型=b.价格类型 and t.生效时间<b.生效时间)
      

  2.   

    Select max(生效日期),货品,价格类型,价格 from Price group by 货品,价格类型,价格
    union all
    Select 生效日期,货品,价格类型,价格 from Price group by 货品,价格类型,价格
    where to_char(生效日期,'yyyy/mm/dd')= select to_char(sysdate,'yyyy/mm/dd') from dual;
      

  3.   

    Select max(生效日期),货品,价格类型,价格 from Price group by 货品,价格类型,价格
    union all
    Select 生效日期,货品,价格类型,价格 from Price 
    where to_char(生效日期,'yyyy/mm/dd')= select to_char(sysdate,'yyyy/mm/dd') from dual;
      

  4.   


    select 货品,价格类型,生效日期,价格
    (select 
    货品,价格类型,生效日期,价格,
    row_number() over(partition by 货品,价格类型 order by 生效日期 desc) rn
    from tb)
    where rn=1--or exists
      

  5.   

    Select max(生效日期),货品,价格类型,价格 from Price group by 货品,价格类型,价格
    union all
    Select 生效日期,货品,价格类型,价格 from Price group by 货品,价格类型,价格
    where to_char(生效日期,'yyyy/mm/dd')= select to_char(sysdate,'yyyy/mm/dd') from dual;