SQL 经典面试题

SQL面试题(1)

用一条SQL语句,怎么显示如下结果
id dptID department name
1 1 设计 张三
2 1 设计 李四
3 2 市场 王五
4 3 售后 彭六
5 4 黑人 陈七

View Code
 1 create table testtable1
2 (
3 id int IDENTITY,
4 department varchar(12)
5 )
6
7 select * from testtable1
8 insert into testtable1 values('设计')
9 insert into testtable1 values('市场')
10 insert into testtable1 values('售后')
11 /*
12 结果
13 id department
14 1 设计
15 2 市场
16 3 售后
17 */
View Code
 1 create table testtable2
2 (
3 id int IDENTITY,
4 dptID int,
5 name varchar(12)
6 )
7 insert into testtable2 values(1,'张三')
8 insert into testtable2 values(1,'李四')
9 insert into testtable2 values(2,'王五')
10 insert into testtable2 values(3,'彭六')
11 insert into testtable2 values(4,'陈七')
12 /*

答案:

 

View Code
1  SELECT testtable2.* , ISNULL(department,'黑人')
2 FROM testtable1 right join testtable2 on testtable2.dptID = testtable1.ID

sql面试题(2)

有表A,结构如下:
A: p_ID p_Num s_id
1 10 01
1 12 02
2 8 01
3 11 01
3 8 03
其中:p_ID为产品ID,p_Num为产品库存量,s_id为仓库ID。请用SQL语句实现将上表中的数据合并,合并后的数据为:
p_ID s1_id s2_id s3_id
1 10 12 0
2 8 0 0
3 11 0 8
其中:s1_id为仓库1的库存量,s2_id为仓库2的库存量,s3_id为仓库3的库存量。如果该产品在某仓库中无库存量,那么就是0代替。

答案:

View Code
1 select p_id ,
2 sum(case when s_id=1 then p_num else 0 end) as s1_id
3 ,sum(case when s_id=2 then p_num else 0 end) as s2_id
4 ,sum(case when s_id=3 then p_num else 0 end) as s3_id
5 from myPro group by p_id

为管理业务培训信息,建立3个表:

S(S#,SN,SD,SA)S#,SN,SD,SA分别代表学号,学员姓名,所属单位,学员年龄

C(C#,CN)C#,CN分别代表课程编号,课程名称

SC(S#,C#,G) S#,C#,G分别代表学号,所选的课程编号,学习成绩

(1)使用标准SQL嵌套语句查询选修课程名称为’税收基础’的学员学号和姓名?

select s# ,sn from s where S# in(select S# from c,sc where c.c#=sc.c# and cn=’税收基础’)

(2) 使用标准SQL嵌套语句查询选修课程编号为’C2’的学员姓名和所属单位?

select sn,sd from s,sc where s.s#=sc.s# and sc.c#=’c2’

(3) 使用标准SQL嵌套语句查询不选修课程编号为’C5’的学员姓名和所属单位?

select sn,sd from s where s# not in(select s# from sc where c#=’c5’)

(4)查询选修了课程的学员人数?

select 学员人数=count(distinct s#) from sc

(5) 查询选修课程超过5门的学员学号和所属单位? 

select sn,sd from s where s# in(select s# from sc group by s# having count(distinct c#)>5)




 



posted @ 2012-03-08 12:12  kensheng  阅读(469)  评论(0编辑  收藏  举报