sql >> Base de Datos >  >> RDS >> Mysql

número_fila por varias columnas

Desafortunadamente, no creo que MySQL proporcione las funciones analíticas que está tratando de usar, es decir, ROWNUMBER() OVER PARTITION;

Sin embargo, eso no significa que no se pueda derivar utilizando otros medios. Prueba esto:

create table myTable (type varchar(50) not null,id int(10) unsigned not null,
date1 varchar(10) default null,date2 varchar(10) default null,diff int unsigned default null
);

insert into myTable (type,id,date1,date2,diff) values ('blue',1,'x1','xxx',18);
insert into myTable (type,id,date1,date2,diff) values ('blue',1,'x2',null,null);
insert into myTable (type,id,date1,date2,diff) values ('red',1,'x1',null,null);
insert into myTable (type,id,date1,date2,diff) values ('blue',2,'x1','xx',15);
insert into myTable (type,id,date1,date2,diff) values ('blue',2,'x2','xx',18);
insert into myTable (type,id,date1,date2,diff) values ('blue',2,'x3',null,null);

select t.type,t.id,t.date1,t.date2,t.rownum
from
(
select mt.type,mt.id,mt.date1,mt.date2,mt.diff,
case 
when mt.id = @curId and mt.type = @curType then @curRow := @curRow + 1 
     else @curRow := 1
END as rownum,
@curId := mt.id,
@curType := mt.type
from myTable mt
join (select @curRow := 0, @curId := -1,@curType="") r
order by mt.id,mt.type
) t;