SQL查询排名函数实例
程序员文章站
2022-03-09 23:46:45
在实际开发中经常会遇到计算某个字段的排名的情况
如下表:totak_sales
现在又如此要求:按sales的逆序排序,要求添加一个sales_rank字段,显示排...
在实际开发中经常会遇到计算某个字段的排名的情况
如下表: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查询排名函数实例的全部内容,希望能给大家一个参考,也希望大家多多支持。