Find the average salary several months back - MySQL

别说谁变了你拦得住时间么 提交于 2019-12-11 09:27:25

问题


I want to find the average salary of the staffs who started work within 8 months ago.

I tried making the code but somehow it's displaying NULL..

SELECT AVG(salary) FROM Staff  
WHERE salary = DATE_SUB(sWDate, INTERVAL 8 MONTH);

Everything is within this table.

Can anyone help me out please? I'm not sure what I've done wrong. Thanks.


回答1:


Why salary = DATE_SUB(sWDate, INTERVAL 8 MONTH)?

WITHIN 8 MONTHS:

SELECT AVG(salary) FROM Staff  
WHERE sWDate <= NOW() AND sWDate >= DATE_SUB(Now(), INTERVAL 8 MONTH);
  • Date_Sub

Another:

SELECT AVG(salary) FROM Staff  
WHERE sWDate <= NOW() AND sWDate >= DATE_ADD(Now(), INTERVAL -8 MONTH);
  • DATE_ADD

PS: It's best that you format Now() according to the date format you have in sWDate to get precise results. Otherwise you can use Year/Month.

e.g.:

SELECT AVG(salary) FROM Staff  
WHERE Date_Format(sWDate,'%Y-%m') <= Date_Format(NOW(),'%Y-%m') 
AND Date_Format(sWDate,'%Y-%m') >= Date_Format(DATE_ADD(Now(), INTERVAL -8 MONTH), '%Y-%m';



回答2:


i think you should check Date field and not Salary for date

SELECT AVG(salary) FROM Staff  
WHERE [DateField] = DATE_SUB(NOW(), INTERVAL 8 MONTH);


来源:https://stackoverflow.com/questions/14654155/find-the-average-salary-several-months-back-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!