1. 程式人生 > >比較複雜的sql面試題

比較複雜的sql面試題

一、分組統計每個班的分數前三名(等同於LeetCode:185. Department Top Three Salaries)

表結構:

create table student(

id varchar(20),-- 編號

class varchar(20),-- 年級

score int-- 分數

);
insert student values('1','一年級',82);

insert student values('2','一年級',95);

insert student values('3','一年級',82);

insert student values('4','一年級',40);

insert student values('5','一年級',20);

insert student values('6','二年級',95);

insert student values('7','二年級',40);

insert student values('8','二年級',3);

insert student values('9','二年級',60);

insert student values('10','二年級',10);

insert student values('11','三年級',70);

insert student values('12','三年級',60);

insert student values('13','三年級',40);

insert student values('14','三年級',90);

sql:

select a.class,a.score 
from student a 
where (select count(*) from student where class=a.class and a.score<score)<3
order by a.class,a.score desc;

二、LeetCode:262. Trips and Users

題目詳見:https://leetcode.com/problems/trips-and-users/

sql:

SELECT Request_at Day,
       ROUND(SUM(IF(Status = 'completed', 0, 1)) / COUNT(*), 2) 'Cancellation Rate'
FROM   Trips t
LEFT   JOIN Users t1 ON t.Client_Id = t1.Users_Id
WHERE  t1.Banned = 'No' AND Request_at BETWEEN '2013-10-01' AND '2013-10-03'
GROUP  BY t.Request_at;