1

我有以下数据:

type   id    date1   date2   diff
-----------------------------------    
blue   1      x1     xxx      18
blue   1      x2     -         -
red    1      x1     -         -
blue   2      x1     xx       15
blue   2      x2     xx       18
blue   2      x3     -        -

我想添加一个row_number来获取这样的数据:

type   id    date1   date2   diff  row_number
---------------------------------------------
blue   1      x1     xxx      18      1
blue   1      x2     -         -      2
red    1      x1     -         -      1
blue   2      x1     xx       15      1
blue   2      x2     xx       18      2
blue   2      x3     -        -       3

即首先按类型排序,然后是 id 和最后日期。

我尝试了以下语法:

Create table t(type char(7), id int(13), date1 date, date2 date, diff int, row_number int) ;

Insert into t(type, id, date1, date2, diff, row_number)

   (SELECT a.type, a.id, a.date1, a.date2, a.diff
    FROM 
       (Select 
            type, id, date1, date2, diff, row_number() over (order by type, id, date1) as r 
        from table) a 
    order by 
       a.type, a.id, a.date1;

上面的语法不起作用,我收到错误消息:

您的 SQL 语法有错误;检查与您的 MYSQL 版本相对应的手册....

我尝试了一种更简单的语法,只是为了查看命令是否像这样工作:

SELECT 
   type,    
   ROW_NUMBER() OVER (PARTITION BY type, id, date1 ORDER By type, lpnr, date1) as t,
   id,
   date1
FROM table;

或者

select 
    row_number() over(order by id), 
    id
from table;

并且仍然收到相同的错误消息。

你能告诉我我做错了什么或者row_number在MYSQL版本中不起作用(我有heidi和workbench)吗?如果命令不起作用,还有其他方法可以做我想做的事吗?

非常感谢你的帮助!

琳达

4

1 回答 1

3

不幸的是,我不相信 MySQL 提供了您尝试使用的分析功能,即ROWNUMBER() OVER PARTITION

但是,这并不意味着它不能使用其他方式得出。试一试:

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;
于 2013-02-21T10:04:12.170 回答