日期:2014-05-17  浏览次数:20431 次

找出课表中教师最先上课的记录,请前辈指点!小弟先感谢了!
数据结构:
id 教师姓名 课程名称 上课时间 移动电话
1   张三  课程a  1-2  13888888888
2   张三  课程b  2-3  13888888888
3   王五  课程c  2-3  13899999999
4   王五  课程c  4-1  13899999999

(注:上课时间中 1-2,表示星期1第二2节课)

问题:想找出数据教师最先上课的记录(教师姓名,课程名称,上课时间,移动电话),请前辈指点!小弟先感谢了!





------解决方案--------------------
SQL code

-->try
select 教师姓名,课程名称,上课时间,移动电话 from
(
    select row_number() over(partition by 教师姓名 order by 教师姓名,left(上课时间,1),right(上课时间,1)) rn,* from @test
)t
where t.rn=1

------解决方案--------------------
如果你表中的ID是根据时间先后顺序排的,那直接用下面的就可以了
SQL code

select * from @test t
where not exists(select 1 from @test where t.教师姓名=教师姓名 and t.ID>ID)

------解决方案--------------------
declare @test table(id int,教师姓名 nvarchar(5),课程名称 nvarchar(20),上课时间 varchar(3),移动电话 varchar(15))
insert into @test
select 1,N'张三',N'课程a','1-2',13888888888 union all
select 2,N'张三',N'课程b','2-3',13888888888 union all
select 3,N'王五',N'课程c','2-3',13899999999 union all
select 4,N'王五',N'课程c','4-1',13899999999

select id,教师姓名,课程姓名,left(上课时间,1)as 时间1,right(上课时间,1)as 时间2,移动电话 into #tb from @test 

select * from @test where exists (select top 1 * from #tb order by 时间1,时间2)

------解决方案--------------------
SQL code

-->测试数据
declare @galenkeny table(id int,教师姓名 nvarchar(5),课程名称 nvarchar(20),上课时间 varchar(3),移动电话 varchar(15))
insert into @galenkeny
select 1,N'张三',N'课程a','1-2',13888888888 union all
select 2,N'张三',N'课程b','2-3',13888888888 union all
select 3,N'王五',N'课程c','2-3',13899999999 union all
select 4,N'王五',N'课程c','4-1',13899999999

--开始查询
--select id,教师姓名,课程名称,left(上课时间,1)as 时间1,right(上课时间,1)as 时间2,移动电话 into #tb from @galenkeny  
--select * from #tb
select * from @galenkeny where id=(select top 1 id from #tb order by 时间1,时间2)
-->结果集
-------------------------------------------------
/*
id     教师姓名  课程名称  上课时间    移动电话
1    张三    课程a     1-2      13888888888
*/