SQL查询排名函数实例
meaijojo 人气:0本文主要讲解SQL查询排名函数实例,比较实用,希望能给大家做一个参考。
在实际开发中经常会遇到计算某个字段的排名的情况
如下表:totak_sales
现在又如此要求:按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;
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;
结果:
或:
复制代码 代码如下:
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;
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;
结果:
由上面的方案,我们可以继续推测,如何选出某项来呢?
比如排名为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;
(
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;
当然,此时如果将顺序修改为3的话,就不能很好的查找到内容了,这个还是一个弊端,需进行修改,待续
以上就是SQL查询排名函数实例的全部内容,希望能给大家一个参考,也希望大家多多支持。
加载全部内容