SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_position
-- ----------------------------
DROP TABLE IF EXISTS `t_position`;
CREATE TABLE `t_position` (
`id` int(0) NOT NULL COMMENT '主键ID',
`start_md` int(0) NULL DEFAULT NULL COMMENT '开始距离',
`end_md` int(0) NULL DEFAULT NULL COMMENT '结束距离',
`positon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '所在地址',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_position
-- ----------------------------
INSERT INTO `t_position` VALUES (1, 100, 121, '龙山路103号');
INSERT INTO `t_position` VALUES (2, 121, 172, '龙山路103号');
INSERT INTO `t_position` VALUES (3, 172, 254, '龙山路103号');
INSERT INTO `t_position` VALUES (4, 254, 277, '解放路440号');
INSERT INTO `t_position` VALUES (5, 277, 298, '解放路440号');
INSERT INTO `t_position` VALUES (6, 298, 401, '团结路205号');
INSERT INTO `t_position` VALUES (7, 401, 422, '人民西路97号');
INSERT INTO `t_position` VALUES (8, 422, 469, '人民西路97号');
INSERT INTO `t_position` VALUES (9, 469, 501, '龙山路103号');
INSERT INTO `t_position` VALUES (10, 501, 537, '龙山路103号');
SET FOREIGN_KEY_CHECKS = 1;
id | start_md | end_md | position |
---|---|---|---|
1 | 100 | 121 | 龙山路103号 |
2 | 121 | 172 | 龙山路103号 |
3 | 172 | 254 | 龙山路103号 |
4 | 254 | 277 | 解放路440号 |
5 | 277 | 298 | 解放路440号 |
6 | 298 | 401 | 团结路205号 |
7 | 401 | 422 | 人民西路97号 |
8 | 422 | 469 | 人民西路97号 |
9 | 469 | 501 | 龙山路103号 |
10 | 501 | 537 | 龙山路103号 |
想实现基于position相邻的元素相同的行进行分组,同时获取start的最小值和end的最大值,效果如下
start_md | end_md | position |
---|---|---|
100 | 254 | 龙山路103号 |
254 | 298 | 解放路440号 |
298 | 401 | 团结路205号 |
401 | 469 | 人民西路97号 |
469 | 537 | 龙山路103号 |
SQL不会写了,求指教
start_md 和 end_md 如果可以确保连续,则直接 group 即可
select min(start_md) start_md,max(end_md) end_md,position from `t_position` group by position
select
min(t.start_md) as start_md,max(t.end_md) as end_md,t.position
from
(
select p.*,IF(@last_position=p.position, @rowNum, @rowNum:=@rowNum+1) as groupNum,@last_position:=p.position
from t_position p, (select @rowNum:=0, @last_position:=null) r
) t
group by t.position, t.groupNum
order by t.groupNum