码迷,mamicode.com
首页 > 数据库 > 详细

My SQL和LINQ 实现ROW_NUMBER() OVER

时间:2016-07-14 10:17:17      阅读:590      评论:0      收藏:0      [点我收藏+]

标签:

Oracle 和SQL server都有ROW_NUMBER() OVER这个功能函数,主要用于分组排序,而MySQL 却没有

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

 SELECT ROW_NUMBER() OVER (PARTITION BY H.ALARMINDEX ORDER BY H.HANDLETIME DESC) N, H.* FROM M_ALARMHANDLE H,这个语句就是用于分组      排序的语句,后面的where M.N=1是取得分组排序后组中第一行,

对应的My SQL语句为

select HANDLELSH,ALARMINDEX,HANDLESTATUS,HANDLETIME,HANDLEPERSON,HANDLEDESCRIPTION,HANDLETYPE,rank from 
(
 select H.*,@rownum:=@rownum+1 ,
 if(@Group=H.ALARMINDEX,@rank:=@rank+1,@rank:=1) as rank,
 @Group:=H.ALARMINDEX
 from (
 select * from M_ALARMHANDLE order by HANDLETIME DESC 
 ) H ,(select @rownum :=0 , @Group := null ,@rank:=0) a ) result where rank=1;

对应的LINQ语句为

 var M_ALARMHANDLEList = (from HA in dbManager.M_ALARMHANDLE
                                                group HA by HA.ALARMINDEX into HH
                                                from MH in HH
                                                orderby MH.HANDLETIME descending
                                                select new
                                                {
                                                    RowNo = RowNo+1,
                                                    MH.HANDLELSH,
                                                    MH.HANDLEDESCRIPTION,
                                                    MH.HANDLEPERSON,
                                                    MH.HANDLESTATUS,
                                                    MH.HANDLETIME,
                                                    MH.HANDLETYPE,
                                                    MH.ALARMINDEX
                                                }).Where(m=>m.RowNo==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(@Group=H.GroupId,@rank:=@rank+1,@rank:=1) as rank,
 @Group:=H.GroupId
 from (
 select id,GroupId,salary from Wmy order by GroupId asc ,salary desc
 ) H ,(select @rownum :=0 , @Group := null ,@rank:=0) a ) result;

 

 

 

My SQL和LINQ 实现ROW_NUMBER() OVER

标签:

原文地址:http://www.cnblogs.com/wangboke/p/5669277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!