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. 查詢 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
總結
- 上一篇: 消防水监测系统解决方案
- 下一篇: boost::stacktrace::d