sql中的Dense_rank

时间:2017-05-29 14:48:12

标签: sql sql-server window-functions

我有下表' CarN'在sql server

    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'对于前三个记录?

2 个答案:

答案 0 :(得分:3)

密集排名的方式如下:

  1. 分区by子句的第一个分区;这是model。所以这里有两个分区,因为有两个模型
  2. 分区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. 在每个分区中,按order by子句给出排序顺序,即carID。请注意,在分区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. 现在整理所有分区以获得您看到的输出。

答案 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)