從網上收集來的一些面試題和解題思路,加以整理,供參考。
Question 1:
Can you use a batch SQL or store procedure to calculating the Number of Days in a Month?
Answer 1:本月的最後一天(日)就等于該月的總天數

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

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

dateadd(mm,1,cast(

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

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

as datetime))))--下個月的第一天(日期)
Answer 2:下個月1号與本月1号之間的天數就等于該月的總天數

ALTER procedure CalcDays

(

@Year int,

@Month int

)

as

begin

if @Month>12 or @Month<1

begin

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

return

end


declare @NextMonth int;

declare @NextYear int;

if @Month=12


set @NextMonth=1;

set @NextYear=@Year+1;


else


set @NextMonth=@Month+1;

set @NextYear=@Year



declare @StartDate nchar(9);

declare @EndDate nchar(9);

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

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

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

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:

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

case

when price is null then 'unknown'

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

else 'other'


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)

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)

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

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

from

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

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

pivot


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

) as pvt

union

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

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


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





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

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

select row_number() as line_no ,title_id from titles

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

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

select * from #t

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)

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

where sales.title_id = titles.title_id;

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

where

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

and

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

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
...

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

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

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

WITH AvgPrice(type,price)

AS


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


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

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

或:

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

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

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