我有下表' 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'对于前三个记录?
答案 0 :(得分:3)
密集排名的方式如下:
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
car12
小于值car13
,并且此处的默认顺序为ASC
,因此两个记录都是car12
的排名与1 分区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)
让我们根据您的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)