现在的位置: 首页 > 综合 > 正文

SQL面试题小结

2013年12月09日 ⁄ 综合 ⁄ 共 1857字 ⁄ 字号 评论关闭

 

 

我想面试过软件开发的朋友都会碰到
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. 


查询
2010

4
月份
Sales
表中的记录。

select
*
from
Sales where
saleDate>=
'2010-4-1'
and
saleDate<=
'2010-4-30'

这个结果很简单,我们扩展一下。现在查询今天的记录:

select
*
from
Sales where
datediff
(
dd,
SaleDate,
getdate
())=
0

我们在查询这个月的记录:

select
*
from
Sales where
datediff
(
mm,
SaleDate,
getdate
())=
0

或者:

select
*
from
Sales where
month
(
saleDate)=
month
(
getdate
())

5.      



表中有
a

b

c
三列,如果
a>b
则选出
a
否则选出
b
,如果
b>c
选出
b
否则选出
c

select
(
case
when
a>
b then
a else
b end
),((
case
when
b>
c then
b else
c end
))
from
temp

6.      



查询
SaleDetail

goodsName
重复的第一行。

select
(
select
top
1 id from
SaleDetail as
a where
a.
goodsName=
b.
goodsName)
as
id,
goodsName from
 
(
select
distinct
goodsName from
SaleDetail)
as
b

 

 

抱歉!评论已关闭.