一.问题 groupBY分组后取最新一条记录的SQL的解决方案. 二.解决方案 select Message,EventTime from PT_ChildSysAlarms as a where EventTime = (select max(b.EventTime) from PT_ChildSysAlarms as b where a.PtName = b.PtName ) group by Message,EventTime order by EventTime desc
查询中经常遇到这种查询,分组后取每组第一条.分享下一个SQL语句: --根据 x 分组后.根据 y 排序后取第一条 select * from ( select ROW_NUMBER() over(partition by x order by y desc) RowNum ,testTable.* 注:我使用MS SQL 08 R2
使用Group By来实现取最新记录,需要注意一个问题,如果最大时间相同的数据都会被取出来. PS:即使数据字段类型是timestamp,也会登录相同的时间的数据. select A.* from A inner join ( select C,Max(Time) from A group by C ) B on A.C = B.C and A.Time = B.Time
1.取时间最新的记录 不分组有重复(多条CreateTime一样的都是最新记录) select * from test t where pid in ( select PId from Test t where time=(select max(time) from Test t1 where t1.PId=t.PId) group by Pid ) and time=(select max(time) from Test t1 where t1.PId=t.PId) 2.分组后取时间最新的记录
获取分组后取某字段最大一条记录 方法一:(效率最高) select * from test as a where typeindex = (select max(b.typeindex) from test as b where a.type = b.type ); 方法二:(效率次之) select a.* from test a, (select type,max(typeindex) typeindex from test group by type) b where a.type = b
以前在开发的时候遇到过一个需求,就是要按照某一列进行分组后取前几条数据,今天又有同事碰到了,帮解决了之后顺便写一篇博客记录一下. 首先先建一个基础数据表,代码如下: IF OBJECT_ID(N'Test') IS NOT NULL BEGIN DROP TABLE Test END CREATE TABLE Test(ID bigint IDENTITY(1,1),Name nvarchar(50),Department nvarchar(50)) INSERT IN
当使用GROUP BY 分组,默认返回的数据是组中最小的记录即id最小的数据, 当开发中经常会需要分组后将最新的数据放在前面, 为了实现需求,使用了嵌套查询,分别使用order by来排序 SELECT id, from_id, to_id, conversation_id, created_date, has_read, content FROM ( SELECT * FROM message WHERE from_id = 6 OR to_id = 6 ORDER BY created_da
select * from ( select last_comment, row_number() over(partition by employeeid,roadline,stationname order by logindate desc) rn from reocrd ) t where t.rn <=1 这段的意思是,将reocrd表根据员工工号( employeeid),线路(,roadline),站点名称(stationname)分组后,取登录日期(logindate) 最大的那
方法:mysql取分组后最新的一条记录,下面两种方法.一种是先筛选 出最大和最新的时间,在连表查询.一种是先排序,然后在次分组查询(默认第一条),就是最新的一条数据了 #select * from t_assistant_article as a, (select max(base_id) as base_id, max(create_time) as create_time from t_assistant_article as b group by base_id ) as b where
今日做项目的时候,项目中遇到须要将数据分组后,分组中的最大值,想了想,不知道怎么做.于是网上查了查,最终找到了思路,经过比較这个查询时眼下用时最快的,事实上还有别的方法,可是我认为我们仅仅掌握最快的方法即可 .好了,不说废话了! 直接上内容吧:下面数据是通过 SELECT [CustomerCaseNo],[PaymentsTime] FROM [BOMSDatabase].[dbo].[BAL_paymentsSwiftInfo] where StoresNo='zq00000034' gro