SQL刷題系列:SQL作爲一種數據庫查詢和程序設計語言,是從事數據技術人員必備的技能,也是各大公司的數據分析、數據挖掘、數據庫等筆試題必考的一種題。所以,不論大家是轉行還是學習都少不了這一關。爲此,Python數據科學開啓了SQL刷題的系列,希望可以幫助有需要的朋友們。 題目來源:本篇內容爲Leetcode上SQL題庫180 難易程度:中等
▌刷題回顧
【SQL刷題系列】:leetcode178 Rank Scores
【SQL刷題系列】:leetcode183 Customers Who Never Order
▌題目描述
Write a SQL query to find all numbers that appear at least three times consecutively.
寫一段SQL查詢語句,找到所有出現至少連續三次的數字。
+----+-----+ | Id | Num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+
For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.
例如,給定上面的logs表,其中 “1” 是唯一一個出現至少連續三次的數字。
+-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+
▌參考答案
參考1:
select distinct (l1.Num) as ConsecutiveNums from Logs l1 left join Logs l2 on l1.Id = l2.Id - 1 left join Logs l3 on l1.Id = l3.Id - 2 where l1.Num = l2.Num and l2.Num = l3.Num;
參考2:
Select distinct(l1.num) as consecutivenums from Logs l1, Logs l2, Logs l3 where l1.num = l2.num and l2.num = l3.num and l2.id = l1.id+1 and l3.id = l2.id+1;
▌答案解析
參考1:創建將3個自連接表,並通過減法把3個表中3個連續id連接起來。最後使用where條件限制3個連續id對應的num值相等。
參考2:其實和參考1是一個思路,不同的地方是自連接是完全按照原有id來連接的,沒有錯位,而錯位的地方在where的限制條件中:3個id的大小順序用加法實現。