当我使用DENSE_RANK()函数时,我在分区by子句和order子句中使用了相同的列。所有行的Dense_rank结果为1。为什么发生这种情况?
表:
orderid custid
10643 1
10692 1
10702 1
10308 2
10625 2
10759 2
10926 2
10365 3
10507 3
10535 3
10573 3查询:
SELECT orderid, custid ,
DENSE_RANK() OVER (Partition BY custid ORDER BY custid) as desnse_rank
FROM TABLE 结果
orderid custid desnse_rank
10643 1 1
10692 1 1
10702 1 1
10308 2 1
10625 2 1
10759 2 1
10926 2 1
10365 3 1
10507 3 1
10535 3 1
10573 3 1 预期结果(据我对dense_rank()的理解):
orderid custid desnse_rank
10643 1 1
10692 1 1
10702 1 1
10308 2 2
10625 2 2
10759 2 2
10926 2 2
10365 3 3
10507 3 3
10535 3 3
10573 3 3发布于 2018-05-16 07:35:27
按列进行分区和按同一列排序是没有意义的,因为每个分区总是有相同的列值来排序。
您需要的是避免分区。PARTITION BY中的列将告诉排名何时重置为1,并再次启动排名,即当引用的列更改值时。对于您的尝试,当custid将值从1更改为2时,另一个分区开始运行,稠密的秩再次从1开始,这就是为什么您为所有行获得1。
这将给出您想要的结果(只需一个分区!)。
SELECT orderid, custid , DENSE_RANK() OVER (ORDER BY custid) as dense_rank FROM TABLE发布于 2018-05-16 07:41:36
只需使用order by
select orderid,custid
,DENSE_RANK() over (order by custid) rn
from @tabelhttps://stackoverflow.com/questions/50364818
复制相似问题