SQL查询排名函数实例
时间:2021-08-06 09:06:36|栏目:MsSql|点击: 次
在实际开发中经常会遇到计算某个字段的排名的情况
如下表: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 Server 2005数据库还原错误的经典解决方案
栏 目:MsSql
本文标题:SQL查询排名函数实例
本文地址:http://www.codeinn.net/misctech/164584.html