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 的地 3040 条数据 ,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.  查询 20104 月份 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.       表中有 abc 三列,如果 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.       查询 SaleDetailgoodsName 重复的第一行。

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值