SQL ranking function instance and SQL ranking function instance

Source: Internet
Author: User

SQL ranking function instance and SQL ranking function instance

In actual development, it is often possible to calculate the ranking of a field.

Table: totak_sales

Now, this requires that you add a sales_rank field to display the ranking order in reverse order of sales.

Method:

Copy codeThe Code is as follows: 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;

Result:


Or:

Copy codeThe Code is as follows: 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;

Result:

From the above scheme, we can continue to speculate, how to select a certain item?

For example:

Copy codeThe Code is as follows: 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;

Of course, if the order is changed to 3 at this time, the content cannot be found very well. This is still a drawback and needs to be modified, to be continued.

The above is all the content of the SQL query ranking function instance. I hope you can give us a reference and support more.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.