如何将密集等级/分区应用于动物 table? SQL 服务器
How to apply dense rank/ partition to animal table? SQL Server
Table:
animal height width footlength brand price age
------------------------------------------------
cow 3 5 2 fuller 231 8
cow 3 5 2 fuller 242 9
cow 3 5 2 fuller 1000 2
chicken 2 2 2 tyson 11 1
chicken 2 2 2 tyson 11 2
chicken 2 2 2 tyson 11 3
cow 4 5 2 tyson 90 900
cow 4 5 2 tyson 90 900
好的,所以在这个 table 我想要排名第 1、2、3 的组。
因为如果动物的高度、宽度、脚长和品牌相同,则给这些行排名相同。
我在 SQL 中编码的方式让每一行都获得相同的排名。对比 3 个不同的等级。
关于如何更好地理解密集排名和这个问题的任何提示?
您可以按如下方式使用DENSE_RANK
:
SELECT *, DENSE_RANK() OVER (ORDER BY height, width, footlength, brand) rnk
FROM yourTable
ORDER BY rnk, animal, height, width, footlength, brand;
请注意,我们不 need/want 带有 DENSE_RANK
的 PARTITION BY
子句,因为排名将应用于整个 table。使用分区意味着可能会多次出现相同的等级值。
Table:
animal height width footlength brand price age
------------------------------------------------
cow 3 5 2 fuller 231 8
cow 3 5 2 fuller 242 9
cow 3 5 2 fuller 1000 2
chicken 2 2 2 tyson 11 1
chicken 2 2 2 tyson 11 2
chicken 2 2 2 tyson 11 3
cow 4 5 2 tyson 90 900
cow 4 5 2 tyson 90 900
好的,所以在这个 table 我想要排名第 1、2、3 的组。
因为如果动物的高度、宽度、脚长和品牌相同,则给这些行排名相同。
我在 SQL 中编码的方式让每一行都获得相同的排名。对比 3 个不同的等级。
关于如何更好地理解密集排名和这个问题的任何提示?
您可以按如下方式使用DENSE_RANK
:
SELECT *, DENSE_RANK() OVER (ORDER BY height, width, footlength, brand) rnk
FROM yourTable
ORDER BY rnk, animal, height, width, footlength, brand;
请注意,我们不 need/want 带有 DENSE_RANK
的 PARTITION BY
子句,因为排名将应用于整个 table。使用分区意味着可能会多次出现相同的等级值。