SQL does not use ORDER by to find the second idea

Source: Internet
Author: User

Example: Find current salary (to_date= ' 9999-01-01 ') ranked second most employee number emp_no, salary salary, last_name, and first_name, no ORDER BY
CREATE TABLE ' Employees ' (
' Emp_no ' int (one) is not NULL,
' Birth_date ' date not NULL,
' first_name ' varchar (not NULL),
' last_name ' varchar (+) not NULL,
' Gender ' char (1) Not NULL,
' Hire_date ' date not NULL,
PRIMARY KEY (' emp_no '));
CREATE TABLE ' salaries ' (
' Emp_no ' int (one) is not NULL,
' Salary ' int (one) is not NULL,
' From_date ' date not NULL,
' To_date ' date not NULL,
PRIMARY KEY (' emp_no ', ' from_date '));

Solution Ideas:

The method of this problem is more

Method One:

Using two times Max, together with select nesting

The main idea is to combine the multi-layer select nesting with the max () function 1, first using the Max () function to find the highest current salary in salaries, that is, select MAX (Salary) from salaries WHERE to_date = ' 9999-01-01 ' 2, and then use inner join to connect employees and salaries table, the qualification is "the same employee" e.emp_no = s.emp_no, "current" s.to_date = ' 9999-01-01 ' and "non-salary highest" s.salary Not IN (SELECT MAX (salary) from salaries WHERE to_date = ' 9999-01-01 ') 3, to find the highest salary under the above restrictions, that is, for all employees of the sub-high salary SELECT e.emp_no, MAX(s.salary) AS salary, e.last_name, e.first_name  FROM employees AS e INNER JOIN salaries AS s  ON e.emp_no = s.emp_no WHERE s.to_date =  ‘9999-01-01‘ AND s.salary NOT IN (SELECT MAX(salary) FROM salaries WHERE to_date =  ‘9999-01-01‘ )

Method Two:

Use Max to select the largest, use where to limit the maximum value, and then take the largest one

Select A.emp_no,max (b.salary), A.last_name,a.first_name

From employees a INNER join salaries B

On A.emp_no=b.emp_no

Where b.salary< (select Max (salary) from salaries)

and b.to_date = ' 9999-01-01 '

SQL does not use ORDER by to find the second idea

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.