SQL查询排名函数实例

在实际开发中经常会遇到计算某个字段的排名的情况

如下表:totak_sales

https://www.dbs724.com/wp-content/uploads/2023/02/1676892121-2cc7a48cd628d49.jpg

现在又如此要求:按sales的逆序排序,要求添加一个sales_rank字段,显示排名顺序

方法:

SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

结果:

https://www.dbs724.com/wp-content/uploads/2023/02/1676892121-31a0b8643287bf3.jpg
或:

SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales < a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

结果:

https://www.dbs724.com/wp-content/uploads/2023/02/1676892122-42ef3979f4a8d18.jpg

由上面的方案,我们可以继续推测,如何选出某项来呢?

比如排名为5的那项内容:

SELECT * from
(
SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales < a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC
) as tab WHERE tab.sales_rank=5;

https://www.dbs724.com/wp-content/uploads/2023/02/1676892122-a3079355c5d2965.jpg

当然,此时如果将顺序修改为3的话,就不能很好的查找到内容了,这个还是一个弊端,需进行修改,待续

本篇文章到此结束,如果您有相关技术方面疑问可以联系我们技术人员远程解决,感谢大家支持本站!


数据运维技术 » SQL查询排名函数实例