使用ROW_NUMBER 和partition by 解决报表中的查询问题
在报表中遇到一个查询问题: 原始数据如下:
Id cust_id call_date call_result 1 1 2012-03-15 09:00:00 fail 2 1 2012-03-15 09:05:00 number error 3 1 2012-03-15 09:10:00 fail 4 1 2012-03-15 09:15:00 success 5 2 2012-03-15 09:01:00 fail 6 2 2012-03-15 09:06:00 number error 7 2 2012-03-15 09:17:00 fail 8 2 2012-03-15 09:18:00 success 9 3 2012-03-15 09:04:00 fail 10 3 2012-03-15 09:09:00 number error 11 3 2012-03-15 09:19:00 fail 12 3 2012-03-15 09:22:22 success 13 4 2012-03-15 09:07:00 fail 14 4 2012-03-15 09:21:40 success
查询出每个cust_id对应的前三条记录:
思路: 使用ROWNUMBER 和 partition by 对每个cust_id对应的记录产生序号, 然后对产生的序号列操作,产生查询出的结果集。
select Id,cust_id,call_date,call_result from ( select ROW_NUMBER() over(partition by cust_id order by call_date) as [rows],* from cust_result)a where a.rows<=3
列表:
1 1 2012-03-15 09:00:00 fail 2 1 2012-03-15 09:05:00 number error 3 1 2012-03-15 09:10:00 fail 5 2 2012-03-15 09:01:00 fail 6 2 2012-03-15 09:06:00 number error 7 2 2012-03-15 09:17:00 fail 9 3 2012-03-15 09:04:00 fail 10 3 2012-03-15 09:09:00 number error 11 3 2012-03-15 09:19:00 fail 13 4 2012-03-15 09:07:00 fail 14 4 2012-03-15 09:21:40 success
博客地址: | http://www.cnblogs.com/sword-successful/ |
博客版权: | 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。 如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。 |