mysql 5.0基于不同列赋值

yzuktlbb  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(362)

我一直在试图找出如何分配数字(在我的例子中,组编号基于不同列中的值)。我有一个带有数字的表,我试图根据这个数字分配组号。数字是表的顺序,对于几行可以相同。

create table test (
    code varchar(10) primary key,
    num varchar(10) not null,
    name varchar(10) not null,
    surname varchar(10) not null);

insert into test values (1,9,'Tom', 'Smith');
insert into test values (2,9,'Adam','Blake');
insert into test values (3,15,'John','Smith');
insert into test values (4,15,'Adam','XYZ');
insert into test values (5,43,'John','Abc');
insert into test values (6,99,'Adam','Abc');
insert into test values (7,99,'John','Abc');

测试表如下所示:

所需的输出如下所示,其中grp值始终是从1开始的连续数字。

结果代码:

create table result (
    code varchar(10) primary key,
    num varchar(10) not null,
    name varchar(10) not null,
    surname varchar(10) not null,
grp varchar(10) not null);

insert into result values (1,9,'Tom', 'Smith',1);
insert into result values (2,9,'Adam','Blake',1);
insert into result values (3,15,'John','Smith',2);
insert into result values (4,15,'Adam','XYZ',2);
insert into result values (5,43,'John','Abc',3);
insert into result values (6,99,'Adam','Abc',4);
insert into result values (7,99,'John','Abc',4);

这能在不创建任何函数和变量的情况下实现吗?是否有任何伪列来描述它并可以使用它?

yiytaume

yiytaume1#

使用 subquery :

select *, (select count(distinct t1.num) from test t1 where t1.num <= t.num) as grp
from test t;
xt0899hw

xt0899hw2#

可以使用相关子查询:

select t.*,
       (select count(distinct t2.num)
        from test t2
        where t2.num <= t.num
       ) as grp
from test t;

更有效的方法是使用变量:

select t.*,
       (@grp := if(@n = t.num, @grp,
                   if(@n := t.num, @grp + 1, @grp + 1)
                  )
       ) as grp
from (select t.*
      from test t
      order by t.num
     ) t cross join
     (select @grp := 0, @n := -1) params;

相关问题