天天看點

面試題解(3):SQL

從網上收集來的一些面試題和解題思路,加以整理,供參考。

Question 1:

  Can you use a batch SQL or store procedure to calculating the Number of Days in a Month?

Answer 1:本月的最後一天(日)就等于該月的總天數

面試題解(3):SQL

select datepart(dd,  --最後一天的日期(日)就等于該月的總天數

面試題解(3):SQL

 dateadd(dd,-1,   --上個月的最後一天(日期)

面試題解(3):SQL

  dateadd(mm,1,cast(

面試題解(3):SQL

      cast(year(getdate()) as varchar)+'-'+  --年份

面試題解(3):SQL

      cast(month(getdate()) as varchar)+'-01' --月、日

面試題解(3):SQL

      as datetime))))--下個月的第一天(日期)

Answer 2:下個月1号與本月1号之間的天數就等于該月的總天數

面試題解(3):SQL

ALTER procedure CalcDays

面試題解(3):SQL

(

面試題解(3):SQL

 @Year int,

面試題解(3):SQL

 @Month int

面試題解(3):SQL

)

面試題解(3):SQL

as

面試題解(3):SQL

begin

面試題解(3):SQL

 if @Month>12 or @Month<1

面試題解(3):SQL

 begin

面試題解(3):SQL

  print 'Month值應該在1~12之間!';

面試題解(3):SQL

  return

面試題解(3):SQL

 end

面試題解(3):SQL
面試題解(3):SQL

 declare @NextMonth int;

面試題解(3):SQL

 declare @NextYear int;

面試題解(3):SQL

 if @Month=12

面試題解(3):SQL
面試題解(3):SQL

  set @NextMonth=1;

面試題解(3):SQL

  set @NextYear=@Year+1;

面試題解(3):SQL
面試題解(3):SQL

 else

面試題解(3):SQL
面試題解(3):SQL

  set @NextMonth=@Month+1;

面試題解(3):SQL

  set @NextYear=@Year

面試題解(3):SQL
面試題解(3):SQL
面試題解(3):SQL

 declare @StartDate nchar(9);

面試題解(3):SQL

 declare @EndDate nchar(9);

面試題解(3):SQL

 set @StartDate=Cast(@Month as nchar(2)) + '/1/' + Cast(@Year as nchar(4));

面試題解(3):SQL

 set @EndDate=Cast(@NextMonth as nchar(2)) + '/1/' + Cast(@NextYear as nchar(4));

面試題解(3):SQL

 SELECT DATEDIFF(day, Cast(@StartDate as datetime), Cast(@EndDate as datetime)) AS NumberOfDays

面試題解(3):SQL

end

Question 2:

  Can you use a SQL statement to calculating it! (SQL Server 2K中的pubs資料庫,下同)

  How can I print "10 to 20" for books that sell for between $10 and $20,"unknown" for books whose price is null, and "other" for all other prices? 

Answer:

面試題解(3):SQL

select title, price as '此列僅供參考用',price=

面試題解(3):SQL

 case 

面試題解(3):SQL

  when price is null then 'unknown'

面試題解(3):SQL

  when price>10 and price<20 then '10 to 20'

面試題解(3):SQL

  else 'other'

面試題解(3):SQL
面試題解(3):SQL

from titles

Question 3:     

  How can I find authors with the same last name?(SQL Server 2K中的pubs資料庫,下同)

  You can use the table authors in datatabase pubs. I want to get the result as below:

  Output:

  au_lname                                 number_dups 

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

  Ringer                                   2

  (1 row(s) affected) 

面試題解(3):SQL

  select au_lname,number_dups=count(1) from authors group by au_lname

Question4:

  Can you create a cross-tab report in my SQL Server!

  How can I get the report about sale quality for each store and each quarterand the total sale quality for each quarter at year 1993?

  You can use the table sales and stores in datatabase pubs.

  Table Sales record all sale detail item for each store. Column store_id is the id of each store, ord_date is the order date  of each sale item, and column qty is the sale qulity. Table stores record all store information.

  I want to get the result look like as below:

Output:

stor_name                                        Total       Qtr1        Qtr2        Qtr3        Qtr4        

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

Barnum's                                             50          0           50          0             0

Bookbeat                                             55          25          30         0             0

Doc-U-Mat: Quality Laundry and Books  85           0           85          0             0

Fricative Bookshop                               60          35          0           0            25

Total                                                 250         60          165         0           25 

Answer:(可以動态拼接SQL來實作,也可以使用SQL Server 2K5中的PIVOT)

面試題解(3):SQL

select stor_name, isnull([1],0)+isnull([2],0)+isnull([3],0)+isnull([4],0) as 'Total', 

面試題解(3):SQL

 isnull([1],0) as 'Qtr1', isnull([2],0) as 'Qtr2', isnull([3],0) as 'Qtr3', isnull([4],0) as 'Qtr4'

面試題解(3):SQL

from

面試題解(3):SQL

(select stor_name,sales.stor_id,DATEPART(qq, ord_date) as Quarty,qty from sales,stores

面試題解(3):SQL

  where sales.stor_id=stores.stor_id and year(sales.ord_date)=1993) as tmp

面試題解(3):SQL

pivot

面試題解(3):SQL
面試題解(3):SQL

 sum(qty) for Quarty in ([0],[1],[2],[3],[4])

面試題解(3):SQL

) as pvt

面試題解(3):SQL

union

面試題解(3):SQL

select 'total', sum(isnull([1],0))+sum(isnull([2],0))+sum(isnull([3],0))+sum(isnull([4],0)) as 'Total', 

面試題解(3):SQL

 sum(isnull([1],0)) as 'Qtr1', sum(isnull([2],0)) as 'Qtr2', sum(isnull([3],0)) as 'Qtr3', sum(isnull([4],0)) as 'Qtr4'

面試題解(3):SQL
面試題解(3):SQL

(select sales.stor_id,DATEPART(qq, ord_date) as Quarty,qty from sales,stores

面試題解(3):SQL
面試題解(3):SQL
面試題解(3):SQL
面試題解(3):SQL
面試題解(3):SQL

Question 5: 

How can I add row numbers to my result set?

In database pubs, have a table titles , now I want the result shown as below,each row have a row number, how can you do that?

Result:

line-no     title_id 

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

1           BU1032

2           BU1111

3           BU2075

4           BU7832

5           MC2222

6           MC3021

7           MC3026

8           PC1035

9           PC8888

10          PC9999

11          PS1372

12          PS2091

13          PS2106

14          PS3333

15          PS7777

16          TC3218

17          TC4203

18          TC7777 

面試題解(3):SQL

--可以直接用SQL Server 2005提供的row_number()函數

面試題解(3):SQL

select row_number() as line_no ,title_id from titles

面試題解(3):SQL

--SQL Server 2000中可以借助于臨時表

面試題解(3):SQL

select line_no identity(int,1,1),title_id into #t from titles

面試題解(3):SQL

select * from #t

面試題解(3):SQL

drop table #t

Question 6: 

Can you tell me what the difference of two SQL statements at performance of execution?

Statement 1:

if NOT EXISTS ( select * from publishers where state = 'NY') 

    begin

        SELECT 'Sales force needs to penetrate New York market'

    end

else

        SELECT 'We have publishers in New York'

Statement 2:

if EXISTS ( select * from publishers where state = 'NY') 

Answer:(我也不知道答案。)

    一個說法是NOT EXISTS内部是由EXISTS來實作的,但我在publishers表中構造了4+百萬條記錄,上面兩條SQL的執行計劃完全相同(In Server Server 2005),各執行計劃的占50%,并沒有發現有差異。

Question 7: 

  How can I list all California authors regardless of whether they have written a book?

  Indatabase pubs, have a table authors and titleauthor , table authors has a column state, and titleauthor have books each author written. 

  CA behalf of california in table authors.

Answer :

  “标準”答案是:SELECT * FROM  authors WHERE state='CA' AND EXISTS 

 (SELECT * FROM titleauthor WHERE authors.au_id=titleauthor.au_id)

  但我覺得題目有問題,按照題目的意思,隻要找出State='CA'的Authors就行了(regardless of whether they have written a book),select * from  authors where state='CA',沒有必要去Join其他的表。

Question 8:

  How can I get a list of the stores that have bought both 'bussiness' and 'mod_cook' type books?

  In database pubs, use three table stores,sales and titles to implement this requestment.

  Now I want to get the result as below:    

  stor_id   stor_name                                                                   

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

  ...   

  7896         Fricative   Bookshop   

Answer:(也可以不用臨時表,而改用SQL Server 2005中的CTE)

面試題解(3):SQL

select sales.stor_id,titles.[type] into #SaleTitle from sales,titles

面試題解(3):SQL

 where sales.title_id = titles.title_id;

面試題解(3):SQL

select distinct stores.stor_id, stores.stor_name from stores,#SaleTitle 

面試題解(3):SQL

 where

面試題解(3):SQL

 'business' in (select #SaleTitle.[type] from #SaleTitle  where stores.stor_id=#SaleTitle.stor_id)

面試題解(3):SQL

 and

面試題解(3):SQL

 'mod_cook' in (select #SaleTitle.[type] from #SaleTitle  where stores.stor_id=#SaleTitle.stor_id);

面試題解(3):SQL

drop table #SaleTitle;

Question 9:

 How can I list non-contignous data?

In database pubs, I create a table test using statement as below, and I insert several row as below

create table test

( id int primary key )

go

insert into test values (1 )

insert into test values (2 )

insert into test values (3 )

insert into test values (4 )

insert into test values (5 )

insert into test values (6 )

insert into test values (8 )

insert into test values (9 )

insert into test values (11)

insert into test values (12)

insert into test values (13)

insert into test values (14)

insert into test values (18)

insert into test values (19)

Now I want to list the result of the non-contignous row as below,how can I do it?

Missing after Missing before 

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

6             8

9             11

...

面試題解(3):SQL

select Test1.id as 'Missing after', Test2.id as 'Missing before' 

面試題解(3):SQL

from test as Test1,test as Test2 where Test1.id+1 not in (select ID from Test) 

面試題解(3):SQL

 and Test2.id=(select min(id) from test where id>Test1.id)

Question10: 

How can I list all book with prices greather than the average price of books of the same type?

Indatabase pubs, have a table named titles , its column named price meanthe price of the book, and another named type mean the type of books.

Now I want to get the result as below:

type         title                                                                            price                 

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

business     The Busy Executive's Database Guide                                              19.9900

面試題解(3):SQL

WITH AvgPrice(type,price) 

面試題解(3):SQL

AS

面試題解(3):SQL
面試題解(3):SQL

    SELECT [type], AVG(price) AS 'price' FROM titles GROUP BY [type]

面試題解(3):SQL
面試題解(3):SQL

SELECT titles.type,title,titles.price FROM titles

面試題解(3):SQL

    JOIN AvgPrice ON titles.price>AvgPrice.price AND titles.[type]=AvgPrice.[type];

面試題解(3):SQL

或:

面試題解(3):SQL

select a.type,a.title,a.price from titles a,

面試題解(3):SQL

(select type,price=avg(price) from titles group by type)b

面試題解(3):SQL

where a.type=b.type and a.price>b.price;

 本文轉自Silent Void部落格園部落格,原文連結:http://www.cnblogs.com/happyhippy/archive/2008/02/03/1063531.html,如需轉載請自行聯系原作者