我有两个带有以下字段的表: W$ `1 X% q1 Q" F' L- N- h, ]
emp_table: emp_id,emp_namesalary_increase: emp_id,inc_date,inc_amount我需要写一个查询,提供员工的详细信息,员工的加薪次数,最大加薪金额的值和加薪日期。这是我到目前为止所拥有的: ( E/ T& E5 M w! h% aSELECT e.*,count(i.inc_amount),max(i.inc_amount)FROM salary_increase AS iRIGHT JOIN emp_table AS eON i.emp_id=e.emp_idGROUP BY e.emp_id;除了授予最高增加金额的日期外,这正确地提出了所有要求。我尝试了以下方法,但都失败了: $ Z" |4 a( G9 I% d: WSELECT e.*,count(i.inc_amount),max(inc_amount),t.inc_dateFROM salary_increase AS iRIGHT JOIN emp_table AS eON i.emp_id=e.emp_idRIGHT JOIN ( SELECT emp_id,inc_date FROM salary_increase WHERE inc_amount=max(inc_amount) GROUP BY emp_id ) AS tON e.emp_id=t.emp_idGROUP BY e.emp_id;这给出了错误的无效使用组功能。有人知道我在做什么吗?, ^ v. P" t4 ^5 z- V
% d+ b5 P6 m5 S解决方案: % y4 D: z$ g2 `$ q1 _
您不能WHEREinc_amount=max(inc_amount)在where这个操作是在句子中执行的,无论是在连接HAVING请尝试以下操作:5 h4 c; x6 t8 i+ U4 N6 i# g
SELECT e.emp_id, e.inc_date, t.TotalInc, t.MaxIncAmountFROM salary_increase AS iINNER JOIN emp_table AS e ON i.emp_id=e.emp_idINNER 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;