SQL 筆試題集錦


1.一道SQL語句面試題,關於group by表內容:

info 表

date result

2005-05-09 win

2005-05-09 lose

2005-05-09 lose

2005-05-09 lose

2005-05-10 win

2005-05-10 lose

2005-05-10 lose

 

如果要生成下列結果, 該如何寫sql語句?

 

              win lose

2005-05-09 2 2

2005-05-10 1 2

答案:

(1) select date, sum(case when result = "win" then 1 else 0 end) as "win", sum(case when result = "lose" then 1 else 0 end) as "lose" from info group by date;

(2) select a.date, a.result as win, b.result as lose

  from

  (select date, count(result) as result from info where result = "win" group by date) as a

  join

  (select date, count(result) as result from info where result = "lose" group by date) as b

  on a.date = b.date;

 

2.表中有A B C三列,用SQL語句實現:當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 table;

 

3.請取出tb_send表中日期(SendTime字段)為當天的所有記錄? (SendTime字段為datetime型,包含日期與時間)

------------------------------------------

select * from tb where datediff(dd,SendTime,getdate())=0

 

4.有一張表,里面有3個字段:chinese,math,english。其中有一條記錄chinese 70分,math 80分,english 58分,請用一條sql語句查詢出所有記錄並按以下條件顯示出來(並寫出您的思路): 

   大於或等於80表示excellent,大於或等於60表示pass,小於60分表示fail。 

       顯示格式: 以上面的chinese 70分,math 80分,english 58分

       chinese              math                english 

       pass                  excellent           fail

 

select (case when chinese >= 80 then "excellent" when chinese >= 60 then "pass" else "fail" end) as chinese,

  (case when math >= 80 then "excellent" when math >= 60 then "pass" else "fail" end) as math,

  (case when english >= 80 then "excellent" when english >= 60 then "pass" else "fail" end) as english

  from grade;

 

5.請用一個sql語句得出結果

從table1,table2中取出如table3所列格式數據,注意提供的數據及結果不准確,只是作為一個格式向大家請教。

如使用存儲過程也可以。

 

table1

 

月份mon 部門dep 業績yj

-------------------------------

一月份      01      10

一月份      02      10

一月份      03      5

二月份      02      8

二月份      04      9

三月份      03      8

 

table2

 

部門dep      部門名稱dname

--------------------------------

      01      國內業務一部

      02      國內業務二部

      03      國內業務三部

      04      國際業務部

 

table3 (result)

 

部門dep 一月份      二月份      三月份

--------------------------------------

      01      10        null      null

      02      10         8        null

      03      null       5        8

      04      null      null      9

------------------------------------------

 

select t1.dep,

sum(case when mon = 1 then yj else 0 end) as jun,

sum(case when mon = 2 then yj else 0 end) as feb,

sum(case when mon = 3 then yj else 0 end) as mar

from

t1 right join t2 on t1.dep = t2.dep

group by t1.dep;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM