Dense_rank 在 sql

Dense_rank in sql

我在 sql 服务器

中有以下 table 'CarN'
    carID      ownerID      Make      Model         Year        Color
    C11         O11         Honda       A           2010        Red       
    C12         blue        Honda       B           2012        Blue      
    C13         O12         Maru        B           2014        Yellow    
    C12         blue        Honda       B           2012        Blue 

当我执行查询时

select  *,dense_Rank() over(partition by model order by carid)
from carN

carID      ownerID      Make      Model         Year        Color     Rank
C11         O11         Honda       A           2010        Red         1
C12         blue        Honda       B           2012        Blue        1
C12         blue        Honda       B           2012        Blue        1
C13         O12         Maru        B           2014        Yellow      2

结果前三个记录怎么碰巧得到相同的数字“1”?

dense rank 的工作方式如下:

  1. 首先按partition by子句进行分区;即 model。所以这里有两个分区,因为有两个模型

分区 1

carID      ownerID      Make      Model         Year        Color
C11         O11         Honda       A           2010        Red

分区 2

carID      ownerID      Make      Model         Year        Color    
C12         blue        Honda       B           2012        Blue      
C13         O12         Maru        B           2014        Yellow    
C12         blue        Honda       B           2012        Blue 
  1. 在每个分区中,按照 carID 子句的 order by 子句给出排名排序。请注意,在分区 2 中,由于两个记录具有相同的 carID,因此它们将被赋予相同的等级,并且由于 car12 的值小于 car13 并且此处的默认顺序为 ASC,因此两个记录car12 与 1
  2. 的排名相同

分区 1

carID      ownerID      Make      Model         Year        Color  rank
C11         O11         Honda       A           2010        Red     1 as it is the only record

分区 2

carID      ownerID      Make      Model         Year        Color    rank
C12         blue        Honda       B           2012        Blue      1
C13         O12         Maru        B           2014        Yellow    2
C12         blue        Honda       B           2012        Blue      1
  1. 现在将所有分区整理在一起以获得您看到的输出。

让我们根据您的 SQL 语句对您的数据集进行分区:

dense_Rank() over(partition by model order by carid)

Model        carID      Rank
  A          C11          1
  -------------------------
  B          C12          1
  B          C12          1
  B          C13          2

第一个分区(模型 A)只有 1 行,所以 Rank = 1

第二个分区的前两行有相同的carID,所以它们都有Rank = 1。如果您希望他们有不同的排名,请添加一个决胜局或使用 ROW_NUMBER:

-- this will still give the same rank when the tie-breaker column is equal
dense_Rank() over(partition by model order by carid, AnotherColumn)


-- guaranteed to give different ranking for each row with a partition
-- if the rows have the same carID, which row gets what number is undetermined
ROW_NUMBER() over(partition by model order by carid)