sql screened packet ordering [first record]

Problem Description

We now have a table titles, a total of four fields, namely emp_no (employee number), title (position), from_date (start time), to_date (end time), record of employees in a period of job title because there will be a promotion, job transfer and the like, which may correspond to multiple emp_no jobs, we want to get to the nearest post all employees, including former employees.


This article describes two methods to achieve results:

method one

Nesting a group by + max () sub query to get the most recent jobs.

Thinking
  1. By taking the maximum of from_date emp_no packet corresponding to each emp_no;
SELECT
    emp_no,
    max( from_date ) AS max_date 
FROM
    titles 
GROUP BY
    emp_no

The results are as follows:
image.png

  1. Take a recent screening of a job information check out the biggest from_date.
SELECT
    t.emp_no,
    t.title 
FROM
    titles t
    LEFT JOIN ( SELECT emp_no, max( from_date ) AS max_date FROM titles GROUP BY emp_no ) et 
ON t.emp_no = et.emp_no AND t.from_date = et.max_date

The results are as follows:
image.png


Method Two

By rank over partition by function implementation, this is now Oracle's unique function, if you use the mysql or sql server there is no way to use.

grammar

Function: adding a pseudo-column according to the conditions based on the original table sorted on.

SELECT
    *,
     RANK() OVER (PARTITION BY emp_no ORDER BY from_date DESC) AS rank
FROM
    titles

RANK() OVER (PARTITION BY emp_no ORDER BY from_date DESC) AS rankThe partitions a table showing emp_no, then the sub-region in descending order according to from_date, generating a ranking result designated rank.
Before we mentioned a problem inside emp_no will correspond to a number of jobs, then a record for each emp_no descending order, then we just need the results of the above query as a child and then screened rank = 1just fine.

The complete code is as follows
SELECT
    * 
FROM
    ( SELECT *, RANK ( ) OVER ( PARTITION BY emp_no ORDER BY from_date DESC ) AS rank FROM titles ) r 
WHERE
    r.rank = '1'

Since my laptop just installed mysql environment, so you would not be able to show effects.


In summary, if you are currently using Oracle, we recommend you use Method Two:

  • The method of Fault Tolerant rate, if there are two titles table and recording emp_no from_date are the same, the method will be given of a single sliver query returns multiple rows;
  • Method II may also be implemented to take the second, third etc. article recording, only a method to choose a maximum or minimum.

peace~

Guess you like

Origin www.cnblogs.com/awesometang/p/12005733.html