create table tb(单据号 int,  进价 int,    货物编码 int)
insert into tb
select 1,       6,      10 union all
select 2,       10,     11 union all 
select 3,       10,     12 union all 
select 4,       10,     10 union all
select 5,       2,      11  
select * from tb a where not exists (select 1 from tb where 货物编码=a.货物编码 and 单据号>a.单据号)
order by 货物编码/*
单据号   进价   货物编码
------------------------
4 10 10
5 2 11
3 10 12
*/
drop table tb

解决方案 »

  1.   

    select t.* from tb t where 进价 = (select max(进价) from tb where 货物编码 = t.货物编码)
      

  2.   

    create table tb(单据号 int,  进价 int,    货物编码 int)
    insert into tb
    select 1,       6,      10 union all
    select 2,       10,     11 union all 
    select 3,       10,     12 union all 
    select 4,       10,     10 union all
    select 5,       2,      11  --一、按货物编码分组取进价最大的值所在行的数据。
    --方法1:
    select a.* from tb a where 进价 = (select max(进价) from tb where 货物编码 = a.货物编码) order by a.货物编码
    --方法2:
    select a.* from tb a where not exists(select 1 from tb where 货物编码 = a.货物编码 and 进价 > a.进价)
    --方法3:
    select a.* from tb a,(select 货物编码,max(进价) 进价 from tb group by 货物编码) b where a.货物编码 = b.货物编码 and a.进价 = b.进价 order by a.货物编码
    --方法4:
    select a.* from tb a inner join (select 货物编码 , max(进价) 进价 from tb group by 货物编码) b on a.货物编码 = b.货物编码 and a.进价 = b.进价 order by a.货物编码
    --方法5
    select a.* from tb a where 1 > (select count(*) from tb where 货物编码 = a.货物编码 and 进价 > a.进价 ) order by a.货物编码drop table tb/*
    单据号         进价          货物编码        
    ----------- ----------- ----------- 
    4           10          10
    2           10          11
    3           10          12(所影响的行数为 3 行)
    */
      

  3.   

    select * from tb where 单据号 in (select max(单据号) from tb group by 货物编码 )
      

  4.   

    先谢谢各位,可能我描述的不够清楚,各位的意见我都试过了,都不是我想要的结果。
    再描述清楚点:表的主键是单据号+编码,是一个进货表,想通过一个SQL语句找出所有货物最近一次进货的进价。
      

  5.   

    有进货日期列,但我想通过一个SQL语句来实现