在一个月黑风高的夜晚,自己无聊学习的SQL的时候,练习,突发奇想的想实现一个功能查询,一张成绩表有如下字段,班级ID,英语成绩,数据成绩,语文成绩如下图 实现 查询出 每个班级英语成绩最高的前两名的记录. 看起来不难的业务,做起来才知道还挺麻烦的,说白了其实就是实现分组后的组内排序,一般不思考的话我们会写出这样的语句: select top 2 English,Classid from CJ group by Classid order by English desc 出现这个错误,应该就明白了
首先,将按条件查询并排序的结果查询出来. mysql order by accepttime desc; +---------------------+------+-----+ | accepttime | user | job | +---------------------+------+-----+ :: | :: | :: | :: | +---------------------+------+-----+ rows in set 然后,从中分组选出最新一条记录. mysql ord
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
场景: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列唯
一.需要实现分组排序并且取组内状态优先级最高的数据 有一张这样的数据表, 需求是根据error_type分组然后取status最小的第一条数据 第一种写法: select t.* from ( select e.* from error_record e where e.status > 0 and e.error_type > 0 order by ) t group by t.error_type 这个写法无法实现我们的需求, 原因是MySQL分组查询时默认按照id从小到大的顺序排列让我们
ROWNUMBER() OVER( PARTITION BY COL1 ORDER BY COL2)用法 今天在使用多字段去重时,由于某些字段有多种可能性,只需根据部分字段进行去重,在网上看到了rownumber() over(partition by col1 order by col2)去重的方法,很不错,在此记录分享下: row_number() OVER ( PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组,在分组内部根据 COL2排序,而此函数计算
查询中经常遇到这种查询,分组后取每组第一条.分享下一个SQL语句: --根据 x 分组后.根据 y 排序后取第一条 select * from ( select ROW_NUMBER() over(partition by x order by y desc) RowNum ,testTable.* 注:我使用MS SQL 08 R2
取SQL分组中的某几行数据 对表中数据分组,有时只需要某列的聚合值:有时却需要返回整行数据,常用的方法有:子查询.ROW_NUMBER.APPLY,总体感觉还是ROW_NUMBER比较直观.测试数据: if OBJECT_ID('testGroup') is not null drop table testGroup GO create table testGroup ( ID int identity primary key, UserID int, OrderID int ) GO inse
语法: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
查询 每个班级英语成绩最高的前两名的记录 原文:https://www.cnblogs.com/hxfcodelife/p/10226934.html select a.Classid,a.English from (select Classid,English,row_number() over(partition by Classid order by English desc) as n from CJ) a where n<=2 另外一种情况:取组内最新的数据select max(cre
比如说有表devicedata: 问题: 现在我想将devicedata这个表中的数据,先按device_id这个字段分组,然后每组中的数据按时间字段ts从大到小的排列, 如何解决呢? 错误的sql:首先分组,然后order by 排序, select * from devicedata GROUP BY device_id, id ORDER BY ts DESC, 但是这条sql查询得到的结果是: 结果是不仅没排序,而且也没分组. 再尝试一下:用子查询 先用order by将数据排序 然后将
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.分组后取时间最新的记录