SQL面试题小结
我想面试过软件开发的朋友都会碰到sql方面的面试题,这个可以说是面试必考的。这里拿几个例子开拓一下思路。
1.
有这样一张表
教师号
星期
是否有课
1
1
有
2
3
有
1
2
有
1
2
有
要得出这样的数据:
姓名
星期一
星期二
星期三
星期四
星期五
1
1
2
Null
Null
Null
2
Null
Null
1
Null
Null
不用管具体的表结构,我们看看如何得到这样的结果:
首先我们通过sql创建一张表,然后插入数据:
create table Course
(
TeacherId int,
Week int,
HasCourse varchar(2)
)
insert into Course values('1','1','有')
我们分析发现,在得到的数据中,星期一这样的字段在原表中是不存在的,所以如何产生这些字段是关键所在,估计这个很多初学者也比较少用,但是却很有用.另外一点就是对于没有课的要显示为空,而不是0.
好了,我们看一下如何统计查询:
select distinct TeacherId as 教师号,
星期一=(select case count(*) when 0 then null else count(*) end from Course where TeacherId=b.TeacherId and Week='1'),
星期二=(select case count(*) when 0 then null else count(*) end from Course where TeacherId=b.TeacherId and Week='2'),
星期三=(select case count(*) when 0 then null else count(*) end from Course where TeacherId=b.TeacherId and Week='3'),
星期四=(select case count(*) when 0 then null else count(*) end from Course where TeacherId=b.TeacherId and Week='4'),
星期五=(select case count(*) when 0 then null else count(*) end from Course where TeacherId=b.TeacherId and Week='5')
from Course b group by TeacherId
2. 查询表User的地30到40条数据,id主键并且不连续.
可以说这是老古董了,不过看两种方法吧:
select top 10 * from [User]
where id not in
(select top 30 id from [User])
select top 10 * from [User]
where id>(select max(id) from (select top 30 id from [User]) as T)
3.
查询SaleDetail表中GoodsName重复出现三次及以上的记录.
select * from (select goodsName, count(goodsName) as c from SaleDetail group
by goodsName)as t where t.c>=3
4
相关文档:
/*
* Source URL: http://jonsion.javaeye.com/blog/511584
*/
1. 获取所有数据库名
1> SELECT name from master..sysdatabases;
2> go
2. 获取所有表名
1> USE master
2> go
1> SELECT name from sysobjects WHERE type='U';
2> go
3. 获取所有字段名
1> SELECT name ......
select top PageSize * from 表
where 条件 and id not in
(select top PageSize*(CurrentPageIndex-1) id from 表 where 条件 order by 排序条件)
order by 排序条件
《PageSize 是GridView中每页显示的信息条数,PageSize*(CurrentPageIndex-1) 在SQL中不识别,需定义变量来替换》 ......
采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setString方法传值即可:
String sql= "select * from users where username=? and password=?;
PreparedStatement preState = conn.prepare ......
1.连接数据库文件
<add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|TimeTracker.mdf;User Instance=true" />
SqlConnectionStringBuilder实例化时,要用到connectionString,如:SqlConnectionStringBuild builder = new SqlCon ......