面试题解(3):SQL

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介:

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

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 10and20,"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;


 本文转自Silent Void博客园博客,原文链接:http://www.cnblogs.com/happyhippy/archive/2008/02/03/1063531.html,如需转载请自行联系原作者

相关实践学习
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
打赏
0
0
0
0
66
分享
相关文章
SQL面试50题------(初始化工作、建立表格)
这篇文章提供了SQL面试中可能会遇到的50道题目的建表和初始化数据的SQL脚本,包括学生、教师、课程和成绩表的创建及数据插入示例。
SQL面试50题------(初始化工作、建立表格)
【Uber 面试真题】SQL :每个星期连续5星评价最多的司机
本文是【SQL周周练】系列的第一篇,作者“蒋点数分”分享了一道来自Uber面试的真题及其解法。题目要求找出每周连续获得5星好评最多的司机ID。文章详细解析了利用SQL窗口函数解决“连续”问题的思路,并通过Python和NumPy生成模拟数据,最终提供Hive SQL解答方案。后续还将涉及Streamlit应用、时间序列分析、AB实验设计等内容,欢迎关注。
152 16
|
12月前
|
SQL
sql面试50题------(1-10)
这篇文章提供了SQL面试中的前10个问题及其解决方案,包括查询特定条件下的学生信息、教师信息和课程成绩等。
sql面试50题------(1-10)
大厂面试高频:4 大性能优化策略(数据库、SQL、JVM等)
本文详细解析了数据库、缓存、异步处理和Web性能优化四大策略,系统性能优化必知必备,大厂面试高频。关注【mikechen的互联网架构】,10年+BAT架构经验倾囊相授。
大厂面试高频:4 大性能优化策略(数据库、SQL、JVM等)
|
12月前
|
SQL
sql面试50题------(21-30)
这篇文章是SQL面试题的21至30题,涵盖了查询不同老师所教课程的平均分、按分数段统计各科成绩人数、查询学生平均成绩及其名次等问题的SQL查询语句。
sql面试50题------(21-30)
|
12月前
|
SQL
sql面试50题------(11-20)
这篇文章提供了SQL面试中的50道题目,其中详细解释了11至20题,包括查询与学号为“01”的学生所学课程相同的学生信息、不及格课程的学生信息、各科成绩统计以及学生的总成绩排名等问题的SQL查询语句。
面试题MySQL问题之使用SQL语句创建一个索引如何解决
面试题MySQL问题之使用SQL语句创建一个索引如何解决
104 1
Java面试题:描述JDBC的工作原理,包括连接数据库、执行SQL语句等步骤。
Java面试题:描述JDBC的工作原理,包括连接数据库、执行SQL语句等步骤。
153 0
Java面试题:简述数据库性能优化的常见手段,如索引优化、SQL语句优化等。
Java面试题:简述数据库性能优化的常见手段,如索引优化、SQL语句优化等。
449 0
常见大数据面试SQL-每年总成绩都有所提升的学生
一张学生成绩表(student_scores),有year-学年,subject-课程,student-学生,score-分数这四个字段,请完成如下问题: 问题1:每年每门学科排名第一的学生 问题2:每年总成绩都有所提升的学生
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等