180. 连续出现的数字
SELECT DISTINCT if(a.num = b.num AND b.num = c.num,a.num,null) AS ConsecutiveNums
FROM Logs a
LEFT OUTER JOIN Logs b
ON a.id+1 = b.id
LEFT OUTER JOIN Logs c
ON a.id+2 = c.id
WHERE if(a.num = b.num AND b.num = c.num,a.num,null) IS NOT NULL
603. 连续空余座位
SELECT a.seat_id AS seat_id
FROM Cinema a
LEFT OUTER JOIN Cinema b
ON a.seat_id + 1 = b.seat_id
LEFT OUTER JOIN Cinema c
ON a.seat_id - 1 = c.seat_id
WHERE a.free = 1 AND (b.free = 1 OR c.free = 1)
ORDER BY seat_id
-- 执行速度慢
SELECT DISTINCT a.seat_id AS seat_id
FROM Cinema a
LEFT OUTER JOIN Cinema b
ON ABS(a.seat_id - b.seat_id) = 1
WHERE a.free = 1 AND b.free = 1
ORDER BY seat_id
613. 直线上的最近距离
-- 方法一:
SELECT MIN(ABS(a.x - b.x)) AS shortest
FROM Point a
LEFT OUTER JOIN Point b
ON a.x <> b.x
-- 方法二:
select x - lag(x) over(order by x) as shortestfrom pointorder by shortestlimit 1offset 1
-- 方法二中的中间输出 select x, lag(x) over(order by x) AS lag_x, -- 取比每个 x 小的值中,但又最靠近x(数值上最大的)的那一个值 x - lag(x) over(order by x) as shortest -- 计算每个 x 与其 lag_x 之间的距离from point
1285. 找到连续区间的开始和结束数字
①先给每个数进行排名
②用这些数减去自己的排名,如果减了之后的结果是一样的,说明这几个数是连续的
(原理:等差数列的值,减去等差数列的值,结果才能是一样的。)
③用logid减去排名得出来的数进行group by,也就是把连续的数全都放在一个一个小组里面,求出每个小组的最大值和最小值就可以了
SELECT MIN(a.log_id) AS START_ID, MAX(a.log_id) AS END_ID
FROM (SELECT log_id, ROW_NUMBER() OVER (ORDER BY log_id ASC) rn,log_id - ROW_NUMBER() OVER (ORDER BY log_id ASC) referenceFROM Logs) a
GROUP BY a.reference
ORDER BY start_id