面试经典考题(一):SQL部分

(1)写出一条Sql语句: 取出表A中第31到第40记录(SQLServer, 以自动增长的ID作为主键, 注意:ID可能不是连续的。)

 

--定义临时表@A并为@A产生数据
declare @A table(id int identity(1,1),testNum int)
declare @i int
set @i=1
while @i<=300
begin
insert into @A(testNum) values(@i)
set @i=@i+2
end
--产生不连续的id(删除部分id)
delete @A where id=1
delete @A where id=10
delete @A where id=33
delete @A where id=40
delete @A where id=42
delete @A where id=99
--解1: 选取@A表中前30条记录,用not in 找出剩下的部分,然后在剩下的部分取前10条既可以找到第30条到40条的记录
select top 10 * from @A where id not in (select top 30 id from @A)
--解2:选取@A表中前30条记录,在取比前30条记录的最大id,然后再在大于id记录中取前10条
select top 10 * from @A where id > (select max(id) from (select top 30 id from @A )as A)

 (2)表假设表@A有100条记录则select select COUNT(*) from @A where testNum=testNum有多少条记录(testNum为@A中字段)

--题目:表@A中字段testNum,假设表@A有100条记录则select select COUNT(*) from @A where testNum=testNum有多少条记录
--
定义临时表
declare @A table(id int identity(1,1),testNum int)
--定义临时变量
declare @i int
set @i=1
while @i<=15
begin
insert into @A(testNum) values(@i)
insert into @A(testNum) values(@i+4)
set @i=@i+2;
end
--查询记录条数
select COUNT(*)from @A
select COUNT(*) from @A where testNum=testNum;
--发现记录条数一样,那为什么呢?
--
个人认为是由于select 是对@A表自身的投影,所以记录为@A的总记录

(3)员工考勤表 A(id,Name,checkinTime),id是为员工编号,Name为员工姓名nvarchar类型,checkinTime为员工打开时间。8点为打卡时间 --打印迟到次数最多的员工信息并打印员工迟到最长一次迟到时间(假设每个员工迟到次数不一样,且每个员工每次迟到时间不一样) 

--定义临时表
declare @A table(id char(5),name nvarchar(10),checkinTime datetime)
insert into @A values('00001','李华','2013-2-3 8:40')
insert into @A values('00001','李华','2013-2-4 9:50')
insert into @A values('00001','李华','2013-2-5 10:59')

insert into @A values('00002','陈美','2013-2-3 6:40')
insert into @A values('00002','陈美','2013-2-4 8:50')
insert into @A values('00002','陈美','2013-2-5 8:59')

insert into @A values('00003','林涛','2013-2-3 11:40')
insert into @A values('00003','林涛','2013-2-4 6:50')
insert into @A values('00003','林涛','2013-2-5 7:59')

select *from @A;
--打印所有员工迟到的总次数
select COUNT(*) as '迟到次数'  from @A where  DATEPART(hour, checkinTime)>=8 
--按员工id,姓名分组打印每个员工对应的迟到次数
select id,name, COUNT(*)as '迟到次数'  from @A where  DATEPART(hour, checkinTime)>=8 group by id,name;
---找出迟到次数最多的那个员工,并打印员工信息,打印迟到次数
  select top 1 id,name, COUNT(*)as '迟到次数'  from @A where  DATEPART(hour, checkinTime)>=8 group by id,name order by '迟到次数' desc
---在已找到的迟到次数最多的员工的所有迟到次数中找出迟到最长的时间。
select  id,(DATEPART(hour, checkinTime)) from @A where   DATEPART(hour, checkinTime)>=8  group by id  

该题还没有写完,只考虑了小时,还有分钟的考虑,这种写法貌似会把句子写得很长,后续思考更好的解决办法。

posted @ 2011-11-16 00:18  焦涛  阅读(2202)  评论(0)    收藏  举报