2013-12-15 77 views
5

我有我需要編寫一個查詢這給員工詳細信息,僱員已收到的次數以下字段SQL SELECT查詢使用聯接,GROUP BY和聚合函數

emp_table: emp_id, emp_name 
salary_increase: emp_id, inc_date, inc_amount 

兩個表工資增長,最高增加額的價值和增加的日期。以下是我迄今爲止:

SELECT e.*, count(i.inc_amount), max(i.inc_amount) 
FROM salary_increase AS i 
RIGHT JOIN emp_table AS e 
ON i.emp_id=e.emp_id 
GROUP BY e.emp_id; 

這個正確給出所有從它的最大增加被授予的日期分開的要求。我試過以下沒有成功:

SELECT e.*, count(i.inc_amount), max(inc_amount), t.inc_date 
FROM salary_increase AS i 
RIGHT JOIN emp_table AS e 
ON i.emp_id=e.emp_id 
RIGHT JOIN 
    (
    SELECT emp_id, inc_date FROM salary_increase 
    WHERE inc_amount=max(inc_amount) GROUP BY emp_id 
    ) AS t 
ON e.emp_id=t.emp_id 
GROUP BY e.emp_id; 

這給出了一個錯誤'無效的使用組功能'。有誰知道我做錯了什麼?

回答

4

你不能做到這一點WHERE inc_amount=max(inc_amount)在where子句中,或者使用HAVING或做它在加入的情況下,試試這個來代替:

SELECT 
    e.emp_id, 
    e.inc_date, 
    t.TotalInc, 
    t.MaxIncAmount 
FROM salary_increase AS i 
INNER JOIN emp_table AS e ON i.emp_id=e.emp_id 
INNER JOIN 
(
    SELECT 
    emp_id, 
    MAX(inc_amount)  AS MaxIncAmount, 
    COUNT(i.inc_amount) AS TotalInc 
    FROM salary_increase 
    GROUP BY emp_id 
) AS t ON e.emp_id = t.emp_id AND e.inc_amount = t.MaxIncAmount;