这种SQL怎么写呢?大家有什么好的想没有?
表结构及数据
class xm datetime
60 张三 2013-03-13 00:18:33.000
60 李四 2013-03-13 00:16:55.000
60 李智 2013-03-13 01:31:26.000
60 李智 2013-03-13 01:31:26.000
70 李智 2013-03-13 01:31:55.000
目标显示
要求:1:招时间升序排
2:同一个班级相同的人仅显示一条
3:显示结果如下
class xm
60 李四
60 张三
60 李智
70 李智
能否给出SQL,谢谢 SQL怎么写呢
[解决办法]
select *
from [tb] as t
where not exists(select 1 from tb where class=t.class and xm=t.xm
and [datetime]<t.[datetime])
ORDER BY [datetime]
[解决办法]
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-14 22:29:13
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
--Jun 17 2011 00:57:23
--Copyright (c) Microsoft Corporation
--Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([class] int,[xm] varchar(4),[datetime] datetime)
insert [huang]
select 60,'张三','2013-03-13 00:18:33.000' union all
select 60,'李四','2013-03-13 00:16:55.000' union all
select 60,'李智','2013-03-13 01:31:26.000' union all
select 60,'李智','2013-03-13 01:31:28.000' union all
select 70,'李智','2013-03-13 01:31:55.000'
--------------开始查询--------------------------
SELECT *
FROM Huang a
WHERE EXISTS (SELECT 1 FROM (
select class,xm,MAX([datetime])[datetime]
from [huang]
GROUP BY class,xm)b WHERE a.class=b.class AND a.xm=b.xm AND a.[datetime]=b.[datetime])
ORDER BY [datetime]
----------------结果----------------------------
/*
class xm datetime
----------- ---- -----------------------
60 李四 2013-03-13 00:16:55.000
60 张三 2013-03-13 00:18:33.000
60 李智 2013-03-13 01:31:28.000
70 李智 2013-03-13 01:31:55.000
*/