我有以下查询:
SELECT @rn:=@rn+1 AS rank, pet_name, pet_count
FROM (
SELECT pet_name, COUNT(*) AS pet_count
FROM pets
WHERE pet_breed="cat"
GROUP BY pet_name
ORDER BY pet_count DESC
) t1, (SELECT @rn:=0) t2
产生如下输出:
1 Kitty 87
2 Smokey 81
3 Bella 80
4 Oreo 63
5 Charlie 63
6 Tiger 62
7 Lucy 62
8 Jack 61
9 Tigger 60
问题是Oreo和Charlie,Tiger和Lucy的排名应该相同,因为它们都是63,所以结果看起来像
1 Kitty 87
2 Smokey 81
3 Bella 80
4 Oreo 63
4 Charlie 63
5 Tiger 62
5 Lucy 62
6 Jack 61
7 Tigger 60
我无法弄清楚调整是否按照我想要的方式进行调整。
建议?
答案 0 :(得分:1)
SELECT IF((@previous = pet_count, @rn, @rn:=@rn+1) AS rank, pet_name, pet_count, @previous := pet_count
FROM (
SELECT pet_name, COUNT(*) AS pet_count
FROM pets
WHERE pet_breed="cat"
GROUP BY pet_name
ORDER BY pet_count DESC
) t1, (SELECT @rn:=0) t2
我实际上并没有尝试这个。但是概念会起作用