获取分组后取某字段最大一条记录 方法一:(效率最高) 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
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.分组后取时间最新的记录
语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN) 简单的说row_number()从1开始,为每一条分组记录返回一个数字,这里的ROW_NUMBER() OVER (ORDER BY xlh DESC) 是先把xlh列降序,再为降序以后的没条xlh记录返回一个序号. 示例: xlh row_num 1700 1 1500 2 1085
/* 分组之后拼接字符串 */ ;with t as( SELECT WorkflowId,Remark FROM dbo.OperatorAutomationProcess GROUP BY WorkflowId,Remark ) , H AS( SELECT WorkflowId, -- 分组的主键 STUFF( ( SELECT '_'+ Remark -- 要拼接的列 FROM t a WHERE b.WorkflowId = a.WorkflowId FOR XML PATH('')
select * from(select row_number() over(partition by IDCARD order by DATATM desc) as rownum,* from (SELECT * FROM TABLENAME)as H1 ) as H where H.rownum = 1 解释:红色为以什么分组 蓝色为以什么排序 紫色为表名 目前是获取表中每个 IDCARD中时间最大的一条
场景:sql server 2008 drop table ID CREATE TABLE ID ( id ,) not null, code int , D date, PRIMARY KEY (id) ) ,getdate()) ,getdate()) ,getdate()) ,getdate()) ,'2017-08-02') ,'2017-08-01') select * from ID 目标: select COUNT(*) from ID group by code 产生code列唯
CREATE TABLE students (course varchar(10), stu_name varchar(10), city varchar(10), score int ) insert into students values('数学','Jack','Tianjin',80); insert into students values('数学','Jordan','Tianjin',80); insert into students values('数学','James','B
select gr,num,dt,(select bys from test where gr=b.gr and dt=b.dt) bys from ( select gr,count(0) num,max(dt) dt from test group by gr ) b //如果有重复项,可用如下语句(针对Mysql的limit,Oracle 可用 rownum<2) select gr,num,dt,(select bys from test where gr=b.gr and dt=b.d