等级函数给出错误的等级

时间:2018-10-09 12:27:00

标签: sql sql-server dense-rank

select distinct a.pattern ,convert(numeric(18,0) ,isnull(b.[DCount]as [DCount]
,DENSE_RANK () OVER ( Partition by a.pattern order by b.[DCount]desc ) as [Rank]  
from a, b

将输出显示为

Pattern Dcount  Rank
A   0   1
A   0   1
A   0   2
A   0   2
B   0   2
B   0   2
B   0   2
B   0   2
C   0   2
C   0   2
C   0   2

所需输出为

Pattern Dcount  Rank
A   0   1
A   0   1
A   0   1
A   0   1
B   0   1
B   0   1
B   0   1
B   0   1
C   0   1
C   0   1
C   0   1

3 个答案:

答案 0 :(得分:0)

以下面的方式使用DENSE_RANK

select * ,DENSE_RANK () OVER ( order by Pattern, Dcount) as rn from t

答案 1 :(得分:0)

也许您只想按dcount进行排名。如果是这样:

select distinct a.pattern, convert(numeric(18,0),
       coalesce(b.DCount, 0) as DCount,
       dense_rank() over (order by b.[DCount] desc) as [Rank]  
from a cross join b;

答案 2 :(得分:0)

尝试一下:您需要按模式,dcount进行分区,并仅按模式进行排序

demo

select *,dense_Rank() over(partition by Pattern,dcount order by Pattern) from tablename