日期:2014-05-18  浏览次数:20936 次

如何实现access当中的first()功能 ?
一表:
物料                 日期                           单号             明细
A                   2006-2-3                   PO0602001       010
A                   2006-3-3                   PO0603001       001
B                   2006-2-3                   PO0602001       010
B                   2006-3-5                   PO0603001       001
B                   2006-3-5                   PO0603001       011
B                   2006-2-8                   PO0602001       010

要得到数据:
A                   2006-3-3                   PO0603001       001
B                   2006-3-5                   PO0603001       011

即按顺序排列后(Order   by   物料,日期   DESC,单号DESC,明细   DESC),取出各物料的第一条记录

------解决方案--------------------
create table T(物料 varchar(10), 日期 datetime, 单号 varchar(10), 明细 varchar(10))
insert T select 'A ', '2006-2-3 ', 'PO0602001 ', '010 '
union all select 'A ', '2006-3-3 ', 'PO0603001 ', '001 '

union all select 'B ', '2006-2-3 ', 'PO0602001 ', '010 '
union all select 'B ', '2006-3-5 ', 'PO0603001 ', '001 '
union all select 'B ', '2006-3-5 ', 'PO0603001 ', '011 '
union all select 'B ', '2006-2-8 ', 'PO0602001 ', '010 '

select ID=identity(int, 1, 1), * into #T from T
order by 物料,日期 DESC,单号 DESC,明细 DESC

select 物料, 日期, 单号, 明细 from #T as tmp
where (select count(*) from #T where 物料=tmp.物料 and ID <=tmp.ID)=1

--result
物料 日期 单号 明细
---------- ------------------------------------------------------ ---------- ----------
A 2006-03-03 00:00:00.000 PO0603001 001
B 2006-03-05 00:00:00.000 PO0603001 011

(2 row(s) affected)