我有一个查询(我在下面显示)生成以下结果集(这会继续增加53,000条记录)
+--------+---------+--------+--------+------------+------------+
| 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 |
...
如果员工编号X可以存储多个工资,我用来获取此套件的查询是:
SELECT * FROM (
SELECT dept_emp.emp_no, @counter := @counter+1 AS counter
FROM (select @counter:=0) AS initvar, dept_emp)
AS employeeFilter
LEFT JOIN(salaries)
ON (salaries.emp_no = employeeFilter.emp_no)
WHERE counter <= (25/100 * @counter) LIMIT 100;
我希望为每个唯一的emp_no获取一行,即最近的工资行(基于to_date
字段)。
+--------+---------+--------+--------+------------+------------+
| 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 |
@counter
实现对于这个问题并不是很重要,但它确实需要保留在该查询中,因为我希望最终构建一个查询,这将产生削减25%的成本部门和@counter
变量允许我按百分比限制结果。
尝试使用DISTINCT select DISTINCT (emp_no)
,但我不是最好用这样的东西,这只会引起更多问题。
答案 0 :(得分:1)
通过附加具有聚合函数(MAX)的子查询来使用此语句。
SELECT * FROM (
SELECT dept_emp.emp_no, @counter := @counter+1 AS counter
FROM (select @counter:=0) AS initvar, dept_emp)
AS employeeFilter
LEFT JOIN(salaries)
ON (salaries.emp_no = employeeFilter.emp_no)
WHERE counter <= (25/100 * @counter) AND
(salaries.emp_no, salaries.to_date) IN
(SELECT sal.emp_no, MAX(sal.to_date)
FROM salaries sal
WHERE sal.emp_no = salaries.emp_no)
LIMIT 100;
答案 1 :(得分:1)
您可以使用JOIN创建与ROW_NUMBER相同的逻辑:
SELECT * FROM (
SELECT t.*,count(*) as rnk
FROM (YourQuery/table) t
INNER JOIN (YourQuery/table) s
ON (t.emp_no = s.emp_no AND t.from_date <= s.from_date))
WHERE rnk = 1
或使用相关查询:
SELECT * FROM (YourQuery) t
WHERE from_date = (select max(s.from_date)
FROM (YourQuery) s
WHERE s.emp_no = t.emp_no)
答案 2 :(得分:1)
<a href="#one">First</a>
<a href="#two">Second</a>
<a href="#three">Third</a>
<div class="wrap">
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</div>