2013-02-21 37 views
0

,我有以下數據:ROW_NUMBER由幾列

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

你是對的,MySQL不支持標準的窗口功能。您需要Tom發佈的解決方法。 – 2013-02-21 10:06:09

回答

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;