mysql - 年薪月薪

标签 mysql sql

我想从这样的表中找出工资差距最大的月份:

  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

但我卡住了,因为我只得到了时间间隔。有人对如何解决这个问题有什么建议吗?

最佳答案

创建一个只有两列的辅助表 salary_month:salarys_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 表,你会得到预期的结果。

关于mysql - 年薪月薪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551919/

相关文章:

php - MySQL LIKE 查询不提取相似数据

php - 如何在 php 中创建电脑计算器脚本

mysql - 如何从表中的某一列中选择具有相同但随机值的行,而无需仅使用一个查询知道该值?

sql - 使用带连接的占位符

c++ - SqlQuery 一个命名占位符多次

mysql - Left Join 2 tables on 1 table

mysql - 所选值的 SQL 平均值

python - sql select group by a having count(1) > 1 equivalent in python pandas?

mysql - 如何限制实体属性值中的属性名称?

php - php 5.6 + 中的 mysql_connect