先寫出Oracle 以及SQL Server中ROW_NUMBER()
SELECT * FROM (SELECT ROW_NUMBER() OVER (PARTITION BY H.ALARMINDEX ORDER BY H.HANDLETIME DESC) N, H.* FROM M_ALARMHANDLE H) M WHERE M.N=1
簡要可以理解為通過實體表生成一個經過排序和分組的中間表,並且此中間表帶自增列(組內自增)例如,

drop table if exists Wmy; create table Wmy (id int ,GroupId int ,salary decimal(10,2) ); insert into Wmy values (1,10,5500.00), (2,10,4500.00), (3,20,1900.00), (4,20,4800.00), (5,40,6500.00), (6,40,14500.00), (7,40,44500.00), (8,50,6500.00), (9,50,7500.00); select id,GroupId,salary,rank from ( select H.id,H.GroupId,H.salary,@rownum:=@rownum+1 , if(@pdept=H.GroupId,@rank:=@rank+1,@rank:=1) as rank, @pdept:=H.GroupId from ( select id,GroupId,salary from Wmy order by GroupId asc ,salary desc ) H ,(select @rownum :=0 , @pdept := null ,@rank:=0) a ) result
以上是MySQL實現ROW_NUMBER(),(腳本摘抄自http://blog.knowsky.com/249710.htm)
