我想获取最近两个月所有员工的薪水差额。
样本数据:http://sqlfiddle.com/#!9/02bfb/1
预期输出:
我尝试过的查询:
SELECT tab1.name, tab1.emp_id
FROM a_test tab1 join a_test tab2
on tab1.id = tab2.id
group by tab1.emp_id
答案 0 :(得分:1)
通过使用join,正如您在过去两个月所说的那样,为什么我使用now()
和month
函数,以及月份列是否包含月份号
select t1.emp_id,t1.name,(t1.salary-t2.salary) as sal_diff from
(
select *
from a_test
where month=Month(now())
) as t1
left join
(
select * from a_test
where month=month(now())-1
) as t2
on t1.emp_id=t2.emp_id
但是,如果您使用月份名称,则在月份列中使用MONTHNAME
,查询将为
select t1.emp_id,t1.name,(t1.salary-t2.salary) as sal_diff from
(
select *
from a_test
where month=MONTHNAME(STR_TO_DATE(month(now()), '%m'))
) as t1
left join
(
select * from a_test
where month=MONTHNAME(STR_TO_DATE(month(now())-1, '%m'))
) as t2
on t1.emp_id=t2.emp_id
答案 1 :(得分:1)
正如我在评论中指出的那样,加入似乎是对此的最佳解决方案:
SELECT a.emp_id,
a.salary-b.salary AS diff,
CONCAT(a.salary,' - ',b.salary) as diff_str
FROM a_test AS a
JOIN a_test AS b
ON a.emp_id = b.emp_id AND a.month_id-1 = b.month_id
WHERE a.month_id = (SELECT MAX(month_id) FROM a_test)
我添加了最后一行,仅返回最近两个月的差额。我本可以做WHERE a.month_id = MONTH(NOW())
,但我选择从数据表中选择上个月。请注意,这里的子查询并不是低效的,因为它只运行了一次。
结果是:
emp_id diff diff_str
1 -26000 27000 - 53000
2 9000 32000 - 23000
答案 2 :(得分:0)
您可以尝试以下方法:
select (parent.salary - (select ch.salary from a_test as ch where ch.emp_id = parent.emp_id order by id desc limit 1,1)) as diff, emp_id, name, salary, month from a_test as parent where month = 'feb';
Sql Fiddle:http://sqlfiddle.com/#!9/52a019/2
您可以添加/更新主查询和子查询中的where条件,以动态获取月份。 如下所示:
where month = MONTHNAME(CURRENT_DATE())