我有一个员工表。 我想知道特定的年度薪水,或者今年是2019年,我想知道我在2018年支付给员工(单人或全部员工)多少薪水。那么如何编写查询。
答案 0 :(得分:0)
您必须获得工作年的百分比,然后乘以薪水。如果joined_date在该年的一月之前,则使用“ 1.00”。
由于您未指定SQL类型,因此我选择了MSSQL,因为我对此最为熟悉。
以下是使用MSSQL的示例:
DECLARE @yearToFindSalaryFor INT = 2018
DECLARE @dateEndOfSalaryYear DATE = ('01/01/' +
CONVERT(VARCHAR(5), (@yearToFindSalaryFor + 1)))
DECLARE @dateStartOfSalaryYear DATE = ('01/01/' +
CONVERT(VARCHAR(5), (@yearToFindSalaryFor)))
SELECT E1.YEARS_WORKED_FOR_YEAR,
E2.sal * E1.YEARS_WORKED_FOR_YEAR AS SALARY_FOR_YEAR, E1.eid
FROM
(
SELECT
CASE WHEN joining_date > @dateEndOfSalaryYear
THEN 0
WHEN joining_date < @dateStartOfSalaryYear THEN 1
-- cast one of the numbers as decimal, otherwise MSSQL will spit out an int value (1 or 0)
-- since DATEDIFF will give INT value not decimal, we have to get 'days' and divide by 365
ELSE DATEDIFF(day, joining_date, @dateEndOfSalaryYear)
/ CAST(365 AS DECIMAL(4, 0))
END
AS YEARS_WORKED_FOR_YEAR, eid FROM Employees
) AS E1
JOIN Employees E2 ON E1.eid = E2.eid