表数据
单号 物料编码 日期       价格 价格类型 
001   605075  2012-07-25  5    结算价
002   605136  2012-08-25  6    采购价
003   605075  2012-08-26  7    采购价
004   605136  2012-09-25   8   采购价查询要求:每个物料编码最近一次的结算价,如果只有采购价,就取最近一次采购价。
需要的结果 是 :
单号 物料编码 日期       价格 价格类型 
001   605075  2012-07-25  5    结算价
004   605136  2012-09-25   8   采购价

解决方案 »

  1.   

    CREATE TABLE 价格信息
    (
     单号 int ,
     物料编码 varchar(8) ,
     日期 datetime,
     价格 int ,
     价格类型 varchar(50)
    )
      

  2.   


    select * from tb t1 where 价格类型='结算价' and not exists(select 1 from tb t2 where t1.物料编码=t2.物料编码 and convert(varchar(10),t1.日期,120)< convert(varchar(10),t2.日期,120) and t1.价格类型=t2.价格类型)
    union all
    select * from  tb t1 where 价格类型='采购价' and (select count(1) from tb t2 where t1.物料编码=t2.物料编码 and t2.价格类型='结算价')<1
    and not exists(select 1 from tb t2 where t1.物料编码=t2.物料编码 and convert(varchar(10),t1.日期,120)< convert(varchar(10),t2.日期,120) and t1.价格类型=t2.价格类型)
      

  3.   

    Select * From (
    SELECT *,row_number() OVER(PARTITION BY [物料编码] Order by [日期] DESC) AS rownum
    From [价格信息]) tb WHere rownum=1
      

  4.   

    select * from (select *,row=row_number()over(partition by 物料编码 order by case when 价格类型='结算价' then 0 else 1 end,日期 desc) from tb)t where row=1