我想从这样的表中找到工资差距最大的月份:
salary_table
ID Salary fromdate todate
1 40000 1994-06-26 1995-06-26
1 41000 1995-06-26 1996-06-25
1 42000 1996-06-25 1996-06-25
2 39000 1998-08-03 1999-08-03
.
.
结果应该是最高和最低月薪差异最大的月份。
我确信我目前的尝试是错误的:
SELECT MAX(`salary`) - MIN(`salary`) AS diff,
YEAR(`from_date`), MONTH(`from_date`) FROM `salaries`
GROUP BY YEAR(`from_date`), MONTH(`from_date`)
ORDER BY diff DESC
但我被困了,因为我只给了间隔。有人建议如何解决这个问题?
答案 0 :(得分:0)
创建一个只有两列的辅助表salary_month
:salary
和s_month
。对于原始salary
表中的每条记录,在salary_month
中插入12条记录,每个区域[fromdate, todate)
中有一条记录。插入的示例过程:
DELIMITER $$
create procedure get_month_salaries()
MODIFIES SQL DATA
begin
declare _df datetime;
declare _salary integer;
declare _counter integer;
declare done boolean default false;
declare cur cursor for select salary, fromdate from salaries;
declare continue HANDLER for not found set done := true;
open cur;
test_loop: loop
fetch cur into _salary, _df;
if done then
LEAVE test_loop;
end if;
set _counter = 0;
while _counter < 12 do
insert into salary_month values (_salary, DATE_ADD(_df, INTERVAL _counter MONTH));
set _counter = _counter + 1;
end while;
end loop test_loop;
close cur;
end$$
DELIMITER ;
然后运行您当前的查询
SELECT MAX(`salary`) - MIN(`salary`) AS diff,
YEAR(`s_month`), MONTH(`s_month`) FROM `salary_month`
GROUP BY YEAR(`s_month`), MONTH(`s_month`)
ORDER BY diff DESC
在salary_month
表上,您将获得预期的结果。