SQL - 分组排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hongchangfirst/article/details/84773366

SELECT *,row_number() over(partition by col1 order by col2) as rn1

这是什么意思呢?

简单的说就是进行分组排序并编号的过程。

row_number()很好理解,给每条记录分配一个行号,从1开始,连续的。那么over (partition by col1 order by col2 desc) 是什么意思呢?就是先按照col1进行分组,然后分别在每个组内按照col2进行降序排序,然后编号。

比如我们有一张表,里边有每个客户所领取的优惠券。现在我们需要拿到每个客户的最近一张优惠券,怎么写SQL呢?

customers_coupons_tbl

CID name date
1 shoe 20181130
1 book 20181212
2 beauty 20181201
2 drug 20181230
2 book 20181212

select *, row_number() over (partition by CID order by date desc) as rn1

from customers_couopns_tbl;

CID name date rn1
1 book 20181212 1
1 shoe 20181130 2
2 beauty 20181230 1
2 drug 20181215 2
2 book 20181212 3

然后我们再在上述表上进行过滤,把rn1不是1的都去掉:

select CID, name, date

from (

select *, row_number() over (partition by CID order by date desc) as rn1

from customers_couopns_tbl;

)

where rn1 = 1;

CID name date
1 book 20181212
2 beauty 20181230

好了,你现在肯定理解了什么是分组排序了。另外,rank()函数也可以替代row_number(),效果是一样的。

原文:http://blog.csdn.net/hongchangfirst/article/details/84773366

作者:hongchangfirst

hongchangfirst的主页:http://blog.csdn.net/hongchangfirst

猜你喜欢

转载自blog.csdn.net/hongchangfirst/article/details/84773366