MySQL-Consecutive Numbers
来源:互联网 发布:诺基亚java游戏接水管 编辑:程序博客网 时间:2024/06/06 11:45
Write a SQL query to find all numbers that appear at least three times consecutively.
+----+-----+| 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.
题目大意:写一个SQL,查出表Logs中连续出现至少3次的数字。
最简单的方法就是直接使用一套SELECT-FROM-WHERE语句
# Write your MySQL query statement belowSELECT DISTINCT L1.Num ConsecutiveNums FROM Logs L1JOIN Logs L2 ON L1.Id + 1 = L2.IdJOIN Logs L3 ON L1.Id + 2 = L3.IdWHERE L1.Num = L2.Num AND L1.Num = L3.NumORDER BY L1.Num
上面两种方法可以用于找到至少三次连续出现的数字,如果将连续出现的数字扩展到N个,按照上面思路写出的SQL语句就会比较长。因此可以用下面这种方式来查询:
SELECT DISTINCT NumFROM ( SELECT Num, CASE WHEN @prev = Num THEN @count := @count + 1 WHEN (@prev := Num) IS NOT NULL THEN @count := 1 END CNT FROM Logs, (SELECT @prev := NULL) X ORDER BY Id) AS AWHERE A.CNT >= N
0 0
- MySQL-Consecutive Numbers
- 题目5:MySQL----------Consecutive Numbers
- Consecutive Numbers
- Consecutive Numbers
- Consecutive Numbers
- Consecutive Numbers
- LeetCode | Consecutive Numbers
- [leetcode] Consecutive Numbers
- consecutive numbers 180
- LeetCode:Consecutive Numbers
- Leetcode:Consecutive Numbers
- [LeetCode] Consecutive Numbers - SQL
- Leetcode: Consecutive Numbers
- [LeetCode][Database]Consecutive Numbers
- LeetCode OJ Consecutive Numbers
- LeetCode_OJ【180】Consecutive Numbers
- [Leetcode] [Database] Consecutive Numbers
- leetcode 180. Consecutive Numbers
- 正则表达式之最短匹配
- window7 下运行hadoop
- java数据结构
- 使用Vs2015开发linux(centos7)程序
- 马化腾的焦虑和小程序的未来到底是什么?
- MySQL-Consecutive Numbers
- Python实现数据库数据导入Excel
- Python 多线程2
- Python HackerRank|DefaultDict Tutorial(from collections import defaultdict)
- SparseArray浅析
- 牛逼程序猿的学习之路
- 链表的7种操作
- Android Studio提交到git中碰到的问题
- 【struts基础】Struts2常用标签总结