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:

如果結(jié)果只有一個(gè)可以用?SELECT customer_number FROM orders GROUP BY customer_number ORDER BY COUNT(*) DESC LIMIT1;

但如果有多個(gè)結(jié)果的話, 可以用?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函數(shù)是用來返回大于的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 的區(qū)別 :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來設(shè)置變量初始值

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;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末鼻百,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子橘券,更是在濱河造成了極大的恐慌党远,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,406評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件营勤,死亡現(xiàn)場(chǎng)離奇詭異灵嫌,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)葛作,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,395評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門寿羞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人进鸠,你說我怎么就攤上這事稠曼。” “怎么了客年?”我有些...
    開封第一講書人閱讀 167,815評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵霞幅,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我量瓜,道長(zhǎng)司恳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,537評(píng)論 1 296
  • 正文 為了忘掉前任绍傲,我火速辦了婚禮扔傅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘烫饼。我一直安慰自己猎塞,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,536評(píng)論 6 397
  • 文/花漫 我一把揭開白布杠纵。 她就那樣靜靜地躺著荠耽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪比藻。 梳的紋絲不亂的頭發(fā)上铝量,一...
    開封第一講書人閱讀 52,184評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音银亲,去河邊找鬼慢叨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛务蝠,可吹牛的內(nèi)容都是我干的拍谐。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼轩拨!你這毒婦竟也來了力穗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,668評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤气嫁,失蹤者是張志新(化名)和其女友劉穎当窗,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體寸宵,經(jīng)...
    沈念sama閱讀 46,212評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡崖面,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,299評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了梯影。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片巫员。...
    茶點(diǎn)故事閱讀 40,438評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖甲棍,靈堂內(nèi)的尸體忽然破棺而出简识,到底是詐尸還是另有隱情,我是刑警寧澤感猛,帶...
    沈念sama閱讀 36,128評(píng)論 5 349
  • 正文 年R本政府宣布七扰,位于F島的核電站,受9級(jí)特大地震影響陪白,放射性物質(zhì)發(fā)生泄漏颈走。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,807評(píng)論 3 333
  • 文/蒙蒙 一咱士、第九天 我趴在偏房一處隱蔽的房頂上張望立由。 院中可真熱鬧,春花似錦序厉、人聲如沸锐膜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,279評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽道盏。三九已至,卻和暖如春庭再,著一層夾襖步出監(jiān)牢的瞬間捞奕,已是汗流浹背牺堰。 一陣腳步聲響...
    開封第一講書人閱讀 33,395評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工拄轻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人伟葫。 一個(gè)月前我還...
    沈念sama閱讀 48,827評(píng)論 3 376
  • 正文 我出身青樓恨搓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子斧抱,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,446評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,345評(píng)論 0 10
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,464評(píng)論 0 13
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,563評(píng)論 0 23
  • 鞏固常拓、增強(qiáng)、提升辉浦、暢通 中央經(jīng)濟(jì)工作會(huì)議提出弄抬,我國(guó)經(jīng)濟(jì)運(yùn)行主要矛盾仍然是供給側(cè)結(jié)構(gòu)性的,必須堅(jiān)持以供給側(cè)結(jié)構(gòu)性改革...
    華圖劉理文閱讀 2,683評(píng)論 0 0