查询中经常遇到这种查询,分组后取每组第一条.分享下一个SQL语句: --根据 x 分组后.根据 y 排序后取第一条 select * from ( select ROW_NUMBER() over(partition by x order by y desc) RowNum ,testTable.* 注:我使用MS SQL 08 R2
如下图, 计划实现 :按照 parent_code 分组, 取组中code最大值所在的整条记录,如红色部分.(类似hive中: row_number() over(partition by)) select c.* from ( end) as sort_num,(@key_i:=parent_code) as tmp ,@key_i:='') b order by parent_code,code desc) c ; 个人理解, mysql 运行顺序: from >> where >
pig可以轻松获取TOP n.书上有例子 hive中比较麻烦,没有直接实现的函数,可以写udf实现.还有个比较简单的实现方法: 用row_number,生成排名序列号.然后外部分组后按这个序列号多虑,样例代码如下 select a.* from( select 品牌,渠道,档期,count/sum/其它() as num row_number() over (partition by 品牌,渠道 order by num desc ) rank from table_name where 品牌,
写法1: use anypay; select tr.* from (select task_code, max(created_at) as cal from task_log group by task_code ) tl join task_log tr on tl.task_code = tr.task_code and tl.cal = tr.created_at; 写法2: use anypay; SELECT * FROM task_log AS t1 WHERE created_
sql中group by后,获取每组中的前N行数据,目前我知道的有2种方法 比如有个成绩表: 里面有字段学生ID,科目,成绩.我现在想取每个科目的头三名. 1. 子查询 select * from score s where StudentName in (select top 3 StudentName from score where s.Subjects = Subjects group by Subjects,StudentName,Score order by Score desc
前言: 同事的业务场景是,按照cid.author分组,再按照id倒叙,取出前2条记录出来. oracle里面可以通过row_number() OVER (PARTITION BY cid,author ORDER BY id DESC) 表示根据cid,author分组,在分组内部根据id排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的),而mysql数据库就没有这样的统计函数,需要自己写复杂的sql来实现. 使用动态sql来实现 先构造序列号
首先,将按条件查询并排序的结果查询出来. mysql order by accepttime desc; +---------------------+------+-----+ | accepttime | user | job | +---------------------+------+-----+ :: | :: | :: | :: | +---------------------+------+-----+ rows in set 然后,从中分组选出最新一条记录. mysql ord
查询username,根据fundcode分组,按照date倒序,取date最大的一条数据 select * from ( select username, row_number() over(partition by fundcode, order by date desc) rn from usertable ) t -----------------------------------------------------------------------------感谢打赏!