簡體   English   中英

SQL 中的連續數字(Leetcode)

[英]Consecutive Numbers in SQL (Leetcode)

問題是針對表:日志

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+

id 是該表的主鍵。 編寫 SQL 查詢以查找至少連續出現 3 次的所有數字。

我的解決方案如下,Leetcode 不接受。 請幫我找出錯誤。

with temp1 as
(select num, 
       id, 
       row_number () over (partition by num order by id) as r
from logs),  
temp2 as
(select (id-r) as rn, num, count(num)  
from temp1
group by rn, num
having count(num)>=3)
select num as ConsecutiveNums
from temp

嘗試:

with temp as (select num,
  lag(num,1) over (order by id asc)  as preceding_num,
  lead(num,1) over (order by id asc) as succeeding_num
from logs)
select
  distinct num as ConsecutiveNums
from temp
where num = preceding_num
and num = succeeding_num;

演示: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/174

滯后:https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_lag

引線:https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_lead

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM