我想从这样一张桌子上找出工资差距最大的月份:
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
但我被困了,因为我只得到了休息时间。有人有什么建议吗?
最佳答案
创建一个辅助表[cc],它只有两个列:salary_month
和salary
。对于原始s_month
表中的每个记录,在salary
中插入12条记录,每个月在salary_month
范围内插入一条记录。插入的示例过程:
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
在
[fromdate, todate)
表中,您将得到预期的结果。关于mysql - 年薪中的月薪,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46551919/