面试题解(3):SQL


从网上收集来的一些面试题和解题思路,加以整理,供参考。

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
 
begin
  
set   @NextMonth = 1 ;
  
set   @NextYear = @Year + 1 ;
 
end
 
else
 
begin
  
set   @NextMonth = @Month + 1 ;
  
set   @NextYear = @Year
 
end

 
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 '
 
end
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)

Answer:

   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 '
from
(
select  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


   
   
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

Answer:

-- 可以直接用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
    begin
        SELECT 'We have publishers in New York'
    end
Statement 2:
if EXISTS ( select * from publishers where state = 'NY')
    begin
        SELECT 'We have publishers in New York'
    end
else
    begin
        SELECT 'Sales force needs to penetrate New York market'
    end

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)
go

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

Answer:

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

Answer:

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;


 

转载于:https://www.cnblogs.com/happyhippy/archive/2008/02/03/1063531.html

你可能感兴趣的:(面试题解(3):SQL)