简体   繁体   中英

MySQL total expenses of employees in a timeframe

So I need to make a procedure that sums all the expenses from the salaries of employees in a given timeframe. However, some employees might not have been hired from the start of the time frame.

Here is what my Worker table columns are:

Name| Last_Name | email| Date_of_Recruitment | Salary | Newspaper_Name |Password |initial_salary

I want the expenses from January to July and an employee was hired in March, I want his salary to be counted for for March, April, May, June, July only.

Any help would be appreciated

Assuming that your table has just one record per employee, I think you want timestampdiff() :

select sum(salary 
    * timestampdiff(month, greatest('2020-01-01', date_of_recruitment), '2020-07-01')
) total_salaries
from mytable
where date_of_recruitment <= '2020-07-01'

For employees that were hired before July 2020, the logic is to count the elapsed month between the recruitment date and July, and multiply that by the salary. You can then sum() the results over the entire dataset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM