SQL median function instance and SQL median instance

Source: Internet
Author: User

SQL median function instance and SQL median instance

Add a table or total_sales

Table:

SQL statement:

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 = (select (count (*) + 1) div 2 from total_sales );

You can find the intermediate item, count (*) + 1. This 1 must be added. If the total number of items is an odd number of 7, count (*) + 1/2 = 4, if it is 6, then it is 3, all are satisfied. If it is not + 1, it is not satisfied for the odd number, such as 7, count (*)/2 = 3, what we want to find is the location 4.

Result:

The above is all the content of the SQL median 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.