Leetcode 题目

1. Shortest Distance in a Line

https://leetcode.com/articles/shortest-distance-in-a-line/

Table point holds the x coordinate of some points on x-axis in a plane, which are all integers.

Write a query to find the shortest distance between two points in these points.

| x  |

|-----|

| -1  |

| 0  |

| 2  |

The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below:

| shortest|

|---------|

| 1      |

Note: Every point is unique, which means there is no duplicates in table point.

Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis?


2. Find Customer Referee

Given a table customer holding customers information and the referee.


Write a query to return the list of customers NOT referred by the person with id '2'.

For the sample data above, the result is:


一开始想用 SELECT name FROM customer where referee_id !=2 但这无法选择NULL的行, 所以还要加上条件 referee_id is NULL。

3. Customer Placing the Largest Number of Orders 

Query the customer_number from the orders table for the customer who has placed the largest number of orders.

It is guaranteed that exactly one customer will have placed more orders than any other customer.

The orders table is defined as follows:



Results:

如果结果只有一个可以用 SELECT customer_number FROM orders GROUP BY customer_number ORDER BY COUNT(*) DESC LIMIT1;

但如果有多个结果的话, 可以用 select customer_number from customer_number

group by customer_number having count(customer_number) >= all

(select count(customer_number) from customer_number group by customer_number)

all 和any函数是用来返回大于的result

4. Triangle Judgement

A pupil Tim gets homework to identify whether three line segments could possibly form a triangle.However, this assignment is very heavy because there are hundreds of records to calculate. Could you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and z.


SELECT *, CASE WHEN x+y>z AND x+z>y AND y+z>x THEN 'YES' ELSE 'No' END AS triangle FROM triangle

5. Consecutive Available Seats

Several friends at a cinema ticket office would like to reserve consecutive available seats.

Can you help to query all the consecutive available seats order by the seat_id using the following cinema table?


SELECT DISTINCT a.seat_id FROM cinema a JOIN cinema b ON ABS(a.seat_id-b.seat_id) =1 and a.free=true and b.free = true ORDER BY a.seat_id

6. Friend Requests I: Overall Acceptance Rate 

In social network like Facebook or Twitter, people send friend requests and accept others’ requests as well. Now given two tables as below:


Write a query to find the overall acceptance rate of requests rounded to 2 decimals, which is the number of acceptance divide the number of requests. For the sample data above, your query should return the following result:


7.Biggest Single Number

Table my_numbers contains many numbers in column num including duplicated ones.

Can you write a SQL query to find the biggest number, which only appears once.

+---+

|num|

+---+

| 8 |

| 8 |

| 3 |

| 3 |

| 1 |

| 4 |

| 5 |

| 6 |

For the sample data above, your query should return the following result:

+---+

|num|

+---+

| 6 |


SELECT num FROM number GROUP BY num HAVING COUNT(*)=1 ORDER BY num DESC LIMIT 1

或者 SELECT MAX(t.num) AS num FROM (SELECT num FROM number GROUP BY num HAVING COUNT(*) = 1) AS t

8. Managers with at Least 5 Direct Reports

Managers with at Least 5 Direct Reports

SELECT Name FROM Employee AS t1 JOIN (SELECT ManagerId FROM Employee GROUP BY ManagerId HAVING COUNT (ManagerId) >=5) AS t2 ON t1.Id =t2.ManagerId;

9. Tree Note

SELECT id, (CASE WHEN p_id IS NULL THEN 'Root' WHEN id in (SELECT p_id FROM Tree) THEN 'Inner'

ELSE 'Leaf' END) as Type From Tree;

10. Shortest Distance in a Plane


SELECT ROUND (SQRT(MIN((POW(p1.x-p2.x,2)+POW(p1.y-p2.y,2)))),2) AS shortest FROM point_2d p1 JOIN point_2d p2 ON(p1.x<=p2.x AND p1.y<p2.y) OR (p1.x<=p2.x AND p1.y>p2.y) OR (p1.x<p2.x  AND p1.y=p2.y);

11.  Investments in 2016

SELECT SUM (insurance.TIV_2016) AS TIV_2016 FROM insurance WHERE insurance.TIV_2015 IN (SELECT TIV_2015 FROM insurance GROUP BY TIV_2015 HAVING COUNT(*) >1) AND CONCAT(LAT,LON) IN (SELECT CONCAT (LAT,LON) FROM insurance GROUP BY LAT, LON HAVING COUNT(*)=1);

12. Friend Requests II: Who Has Most Friend?

SELECT request_id AS id, COUNT(*) AS num FROM (

SELECT request_id FROM Friend f UNION all SELECT accepter_id FROM Friend f2) AS t

GROUP BY request_id ORDER BY num DESC LIMIT 1

Follow-up:

In the real world, multiple people could have the same most number of friends, can you find all these people in this case?

union 和 union all 的区别 :UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not. There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).

13. Count Student Number in Departments

SELECT department.dept_name, count(student.student_id) AS num FROM student RIGHT OUTER JOIN department on student.dep_id=department.dep_id  GROUP BY department.dept_name;

Right JOIN 和 Right OUTER JOIN

14. Winning Candidate

SELECT Candidate.Name From

(SELECT CandidateId, Count(*) as count FROM Vote GROUP BY CandidateId) AS t

LEFT JOIN Candidate ON t.CandidateId=Candidate.id ORDER BY count DESC LIMIT 1;

15. Get Highest Answer Rate Question

SELECT question_id AS 'survey_log' FROM survey_log GROUP BY question_id ORDER BY COUNT (answer_id) / SUM(IF (action='show',1,0) ) DESC LIMIT 1;

或者用Count (IF(action='show',1,NULL))


15. Second Degree Follower

SELECT follow.follower, count(*) AS num FROM follow join follow f2

ON follow.follower=f2.followee

GROUP BY f2.followee;


16. Find Median Given Frequency of Numbers



SELECT ROUND(AVG(Number),2) AS median FROM (

SELECT Number, Frequency, AccFreq, SumFreq FROM  ((

SELECT  Number,Frequency, @curFreq := @curFreq + Frequency AS AccFreq

FROM  Numbers n, (SELECT @curFreq := 0) r ORDER BY  Number) t1,

(SELECT SUM(Frequency) AS SumFreq FROM Numbers) t2)) t

WHERE AccFreq BETWEEN SumFreq/2 AND SumFreq/2 +Frequency;

User-Defined Variables: 可用set来设置变量初始值

17. Median Employee Salary

SELECT DISTINCT t1.Company, t1.salary FROM (

(SELECT e1.Company, count(1) AS 'rank', e1.salary FROM employees e1

LEFT JOIN employees e2 on e1.Company=e2.Company

WHERE e1.salary <= e2.salary GROUP BY e1.Company, e1.Id, e1.salary) t1 LEFT JOIN

(SELECT Company, COUNT(*) as count FROM employees GROUP BY Company) t2

ON t1.Company=t2.Company) WHERE rank/count BETWEEN 0.5 AND 0.5+1/count;

18. Students Report By Geography

select min(America) as America, min(Asia) as Asia, min(Europe) as Europe from(

SELECT (case when continent = 'America' then @am:=@am+1 when continent = 'Asia' then @as:=@as+1

when continent = 'Europe' then @eu:=@eu+1

end) as rowline,(CASE WHEN continent="America" Then name END) AS America,

(CASE WHEN continent="Asia" Then name END) AS Asia,

(CASE WHEN continent="Europe" Then name END) AS Europe

FROM student_loc,(select @am:=0, @as := 0, @eu:=0) temp

order by name) m group by rowline;


19.Average Salary: Departments VS Company

Create table salary(Id int,employee_id int,amount int,pay_date date);

insert into salary values(1,1,9000,'2017-03-31');

insert into salary values(2,2,6000,'2017-03-31');

insert into salary values(3,3,10000,'2017-03-31');

insert into salary values(4,1,7000,'2017-02-28');

insert into salary values(5,2,6000,'2017-02-28');

insert into salary values(6,3,8000,'2017-02-28');

Create table employee_dept(Id int,department_id int);

insert into employee_dept values(1,1);

insert into employee_dept values(2,2);

insert into employee_dept values(3,2);


SELECT t1.pay_month, t1.department_id, (CASE WHEN dept_avg > com_avg THEN 'higher' WHEN dept_avg<com_avg THEN 'lower' ELSE 'same' END) AS comparison FROM (

(SELECT LEFT(pay_date,7) AS pay_month, department_id, AVG(s.amount) AS dept_avg FROM salary s

LEFT JOIN employee_dept d ON s.employee_id=d.Id GROUP BY LEFT(pay_date,7),department_id) t1 LEFT JOIN (

SELECT LEFT(pay_date,7) AS pay_month,AVG(amount) AS com_avg FROM salary GROUP BY LEFT(pay_date,7)) t2 on t1.pay_month=t2.pay_month);

20.Find Cumulative Salary of an Employee

select a.id, a.month, sum(b.salary) from employees2 a, employees2 b where a.id = b.id and a.month >= b.month and a.month < (select max(month) from employees2 c where a.id = c.id) group by a.id, a.month ORDER BY a.Id, a.Month DESC;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,948评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,371评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,490评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,521评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,627评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,842评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,997评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,741评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,203评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,534评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,673评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,339评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,955评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,770评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,000评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,394评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,562评论 2 349

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,312评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,448评论 0 13
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,437评论 0 23
  • 巩固、增强、提升、畅通 中央经济工作会议提出,我国经济运行主要矛盾仍然是供给侧结构性的,必须坚持以供给侧结构性改革...
    华图刘理文阅读 2,669评论 0 0