LeetCode-The number appearing continuously

1.题目

表结构

-- ----------------------------
-- Table structure for logs
-- ----------------------------
DROP TABLE IF EXISTS `logs`;
CREATE TABLE `logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `num` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of logs
-- ----------------------------
INSERT INTO `logs` VALUES ('1', '1');
INSERT INTO `logs` VALUES ('2', '1');
INSERT INTO `logs` VALUES ('3', '1');
INSERT INTO `logs` VALUES ('4', '4');
INSERT INTO `logs` VALUES ('5', '4');
INSERT INTO `logs` VALUES ('6', '7');

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+

2.示例

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

3.输出

SELECT DISTINCT
    log1.Num AS ConsecutiveNums
FROM
    LOGS log1,
    LOGS log2,
    LOGS log3
WHERE
    log1.Id = log2.Id - 1
AND log2.Id = log3.Id - 1
AND log1.Num = log2.Num
AND log2.Num = log3.Num

猜你喜欢

转载自blog.csdn.net/BeiShangBuZaiLai/article/details/81565465