mysql - SELECT latest date in a group of results distinctly -


i have query (i show below) generating following result set (this goes on 53,000 more records)

+--------+---------+--------+--------+------------+------------+ | emp_no | counter | emp_no | salary | from_date  | to_date    | +--------+---------+--------+--------+------------+------------+ |  10001 |       1 |  10001 |  60117 | 1986-06-26 | 1987-06-26 | |  10001 |       1 |  10001 |  62102 | 1987-06-26 | 1988-06-25 | |  10001 |       1 |  10001 |  66074 | 1988-06-25 | 1989-06-25 | |  10001 |       1 |  10001 |  84917 | 1999-06-23 | 2000-06-22 | |  10001 |       1 |  10001 |  85112 | 2000-06-22 | 2001-06-22 | |  10001 |       1 |  10001 |  85097 | 2001-06-22 | 2002-06-22 | |  10001 |       1 |  10001 |  88958 | 2002-06-22 | 9999-01-01 | |  10002 |       2 |  10002 |  65828 | 1996-08-03 | 1997-08-03 | |  10002 |       2 |  10002 |  65909 | 1997-08-03 | 1998-08-03 | |  10002 |       2 |  10002 |  67534 | 1998-08-03 | 1999-08-03 | |  10002 |       2 |  10002 |  69366 | 1999-08-03 | 2000-08-02 | |  10002 |       2 |  10002 |  71963 | 2000-08-02 | 2001-08-02 | |  10002 |       2 |  10002 |  72527 | 2001-08-02 | 9999-01-01 | ... 

where employee number x can have multiple salaries stored, query i'm using fetch set is:

select * (     select dept_emp.emp_no, @counter := @counter+1 counter      (select @counter:=0) initvar, dept_emp)  employeefilter  left join(salaries)  on (salaries.emp_no = employeefilter.emp_no)  counter <= (25/100 * @counter) limit 100; 

i'm looking single row each unique emp_no, recent salary row (based on to_date field).

+--------+---------+--------+--------+------------+------------+ | emp_no | counter | emp_no | salary | from_date  | to_date    | +--------+---------+--------+--------+------------+------------+ |  10001 |       1 |  10001 |  88958 | 2002-06-22 | 9999-01-01 | |  10002 |       2 |  10002 |  72527 | 2001-08-02 | 9999-01-01 | 

the @counter implementation isn't important issue, need remain in query, i'm looking build query generate cost of cutting 25% of department, , @counter variable allows me limit results percentage.

tried use distinct select distinct (emp_no) i'm not best stuff this, , caused more issues.

you can use join make same logic row_number this:

select * (     select t.*,count(*) rnk     (yourquery/table) t     inner join (yourquery/table) s     on (t.emp_no = s.emp_no , t.from_date <= s.from_date)) rnk = 1 

or correlated query :

select * (yourquery) t from_date = (select max(s.from_date)                     (yourquery) s                    s.emp_no = t.emp_no) 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -