日期:2014-05-19  浏览次数:20529 次

请高手看看,求一个SQL语句,稍微有些难吧!
有表名称和结构如下:
TestTable
KeyID       varchar(4)     Primary   Key
StdID       varchar(2)
SDate       datetime
EDate       datetime
-------------------------------------
有如下记录
KeyID       StdID             SDate                   EDate
A001           T1             2006/10/13         2006/10/15
A002           T1             2006/10/13         2006/11/10
A003           T2             2006/12/01         2006/11/05
A004           T2             2006/12/02         2006/12/08
A005           T2             2006/12/02         2006/12/09
--------------------------------------
想要结果是:不同的StdID,且SDate是最大的记录,如果SDate相同取EDate最大,
既想要的结果为:
KeyID       StdID             SDate                   EDate
A002           T1             2006/10/13         2006/11/10
A005           T2             2006/12/02         2006/12/09
请各位赐教,谢谢!




------解决方案--------------------
declare @a table(KeyID varchar(4) Primary Key,StdID varchar(2),SDate datetime,EDate datetime)
insert @a select 'A001 ', 'T1 ', '2006/10/13 ', '2006/10/15 '
union all select 'A002 ', 'T1 ', '2006/10/13 ', '2006/11/10 '
union all select 'A003 ', 'T2 ', '2006/12/01 ', '2006/11/05 '
union all select 'A004 ', 'T2 ', '2006/12/02 ', '2006/12/08 '
union all select 'A005 ', 'T2 ', '2006/12/02 ', '2006/12/09 '

select stdid,sdate,max(edate) edate from @a group by stdid,sdate
select * from @a a where not exists(select 1 from
(select stdid,sdate,max(edate) edate from @a group by stdid,sdate) b where stdid=a.stdid and edate> a.edate)
------解决方案--------------------
select * from TestTable a
where not exists (select 1 from TestTable where StdID = a.StdID and
(SDate > a.SDate or SDate = a.SDate and EDate > a.EDate))
------解决方案--------------------

create table TestTable(
KeyID varchar(4) Primary Key,
StdID varchar(2),
SDate datetime,
EDate datetime
)
insert TestTable select 'A001 ', 'T1 ', '2006-10-13 ', '2006-10-15 '
union all select 'A002 ', 'T1 ', '2006-10-13 ', '2006-11-10 '
union all select 'A003 ', 'T2 ', '2006-12-01 ', '2006-11-05 '
union all select 'A004 ', 'T2 ', '2006-12-02 ', '2006-12-08 '
union all select 'A005 ', 'T2 ', '2006-12-02 ', '2006-12-09 '

select * from TestTable as tmp
wher