Top n Large elements in Mysql lookup table

Source: Internet
Author: User

Reprint Annotated Source: http://www.cnblogs.com/liangyongrui/p/8622593.html

Top n Large elements in Mysql lookup table

It's easy to write with a program, and you can use a heap to maintain it, but with SQL?

Solution:

Assuming that the field you want to compare is a, to find the top n rows, the answer is count (a line smaller than a) < n rows. (that's a little bit around.) See an example to understand)

Suppose there's a table like this

Id Name Salary
1 Joe 70000
2 Henry 80000
3 Sam 60000
4 Max 90000
5 Janet 69000
6 Randy 85000

Find out the top three salary

SELECT  e1.Name,  e1.SalaryFROM Employee e1WHERE3 >      (        SELECTcount(DISTINCT e2.Salary)        FROM Employee e2        WHERE e2.Salary > e1.Salary      );

Result is

Name Salary
Joe 70000
Henry 80000
Max 90000

Reference: https://leetcode.com/problems/department-top-three-salaries/solution/

Top n Large elements in Mysql lookup table

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.