简体   繁体   中英

Consecutive Numbers in SQL (Leetcode)

The question is for Table: Logs

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

id is the primary key for this table. Write an SQL query to find all numbers that appear at least three times consecutively.

My solution is the following, which Leetcode is not accepting. Kindly help me identify the error.

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

Try:

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;

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM