我有以下sql表;
我需要按intx值对行进行分组,但是此intx值是动态的 因此,没有具体的取值范围。
id, intx, name
"1" "70" "x7"
"2" "99" "x100"
"3" "100" "x100"
"4" "101" "x100"
"5" "69" "x7"
"6" "50" "x5"
我想使用intx将此表分组。
但是,我想将intx的值分组在(intx + 1)和(intx-1)之间
例如; intx值= 100、101和99必须是一组。
使用以下命令;
select a.intx, b.intx,a.name,b.name,MAX(a.intx,b.intx),MIN(a.intx,b.intx)
from t1 a inner join t1 b
on a.intx <=b.intx+1 and a.intx >= b.intx-1 and a.intx<>b.intx
group by MAX(a.intx,b.intx)
但是给我以下结果; a.intx,b.intx,a.name,b.name,MAX,MIN
a.intx b.intx a.name b.name MAX MIN
"69" "70" "x7" "x7" "70" "69"
"100" "99" "x100" "x100" "100" "99"
"101" "100" "x100" "x100" "101" "100"
没有将101放入第二组。
答案 0 :(得分:0)
我不禁感到这个问题缺少一些内容,因此在尝试阐明将规则应用于所提供数据时会发生什么。
drop table if exists t;
create table t (id int, intx int, name varchar(10));
insert into t values
(1, 70 , 'x7'),
(2, 99 , 'x100'),
(3, 100 , 'x100'),
(4, 101 , 'x100'),
(5, 69 , 'x7'),
(6, 50 , 'x5');
select t1.intx midintx,t1.name,t3.name,t1.intx as minintx, t3.intx as maxintx from t t1
join t t2 on t2.intx = t1.intx - 1
join t t3 on t3.intx = t1.intx + 1;
+---------+------+------+---------+---------+
| midintx | name | name | minintx | maxintx |
+---------+------+------+---------+---------+
| 100 | x100 | x100 | 100 | 101 |
+---------+------+------+---------+---------+
1 row in set (0.00 sec)
请注意,由于x3和x5没有3个值,因此仅出现x100和x7。
如果x100下确实出现了98,则
drop table if exists t;
create table t (id int, intx int, name varchar(10));
insert into t values
(1, 70 , 'x7'),
(2, 99 , 'x100'),
(3, 100 , 'x100'),
(4, 101 , 'x100'),
(5, 69 , 'x7'),
(6, 50 , 'x5'),
(7, 98 , 'x100');
+---------+------+------+---------+---------+
| midintx | name | name | minintx | maxintx |
+---------+------+------+---------+---------+
| 99 | x100 | x100 | 99 | 100 |
| 100 | x100 | x100 | 100 | 101 |
+---------+------+------+---------+---------+
2 rows in set (0.00 sec)
根据规则向右看。 请发表评论。