商品采购记录表:商品编号 采购日期 采购价
001 2010-01 10
001 2010-06 12
001 2011-02 14
002 2010-01 20
002 2010-04 20
002 2010-08 22
002 2011-02 24
。
。
。
。现在要求最新采购价,结果应如: 商品编号 采购日期 采购价
001 2011-02 14
002 2011-02 24
。
。
。
001 2010-01 10
001 2010-06 12
001 2011-02 14
002 2010-01 20
002 2010-04 20
002 2010-08 22
002 2011-02 24
。
。
。
。现在要求最新采购价,结果应如: 商品编号 采购日期 采购价
001 2011-02 14
002 2011-02 24
。
。
。
from 商品采购记录表 a
where not exists (select 1 from 商品采购记录表 b
where a.商品编号=b.商品编号 and b.采购日期>a.采购日期)
查出来的的记录数 和 select distinct 商品编号 from 商品采购记录表
结果不一样
如果有多条记录,你可以:
select top 1 * from 采购记录表 a where not exists(select 1 from 采购记录表 where 商品编号=a.商品编号 and 采购日期>a.采购日期)另外,如果你的采购日期用的是datetime,而且用了时分秒,那就很难有几条记录了.
select 商品编号,采购日期
from 商品采购记录表 a
where not exists (select 1 from 商品采购记录表 b
where a.商品编号=b.商品编号 and b.采购日期>a.采购日期)
group by 商品编号,采购日期 having count(*)>1
select * from 商品采购记录表 c ,
(select 商品编号,采购日期
from 商品采购记录表 a
where not exists (select 1 from 商品采购记录表 b
where a.商品编号=b.商品编号 and b.采购日期>a.采购日期)
group by 商品编号,采购日期 having count(*)>1) tb
where c.商品编号=tb.商品编号 and c.采购日期=tb.采购日期