我有以下数据:
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)吗?如果命令不起作用还有其他方法可以做我想做的事吗?
非常感谢你的帮助!
琳达
答案 0 :(得分:1)
不幸的是,我不相信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;