获取员工每个月的工资

Get employee's salary for each month

我有 2 table [EmployeeInfo] [EmployeeInfoHistory] 并且我在这个 table 中存储员工的工资。我能够根据各自的员工和员工获得员工的薪水。

但我想显示员工每月的工资,如下所示。

我的结构适用于 [EmployeeInfo]:

Create Table [EmployeeInfo]
(
  EmpID Int,
  Salary Int,
  EmployementStatus Varchar(50),
  HiringDate Date
);

我的结构适用于 [EmployeeInfoHistory]:

Create Table [EmployeeInfoHistory]
(
  EmpID Int,
  NewSalary Int,
  UpdatedEmployementStatus Varchar(50),
  PromotionDate Date
);

信息数据 Table:

EmpID  Salary  Status   HiringDate
1      20000   Intern   2017-10-02
2      30000   Jr. DBA  2017-11-01

InfoHistory 数据Table:

EmpID  Salary  UpdatedStatus   PromotionDate
1      25000   Jr. DBA         2018-01-01
2      45000   Sr. DBA         2018-01-01

我想以给定格式列出日期。

EmpID   Month     Salary  Status
1       October   20k     Intern
1       November  20k     Intern
1       December  20k     Intern
1       January   25k     Jr. DBA
2       November  30k     Jr. DBA
2       December  30k     Jr. DBA
2       January   45k     Sr. DBA

提前致谢

获取历史salary列数据的sumtable作为员工id对应的所需月份

您需要 table 带日期。在这里,我使用 CTE 制作了一个 table,我加入了你的 tables。

; WITH DS AS
(
    SELECT cast (Dateadd(year, -25, getdate()) AS date) as [Date]
        UNION all
    SELECT dateadd(Month, 1, [Date])
        FROM DS
        WHERE Date < getdate()
)
Select EMP.EmpID, DateName(month, DS.[Date]) as [Month], isnull(HIS.NewSalary, EMP.Salary) as Salary, ISNULL(HIS.UpdatedStatus, EMP.EmployementStatus) as [Status]
from EmployeeInfo as EMP
    inner join DS 
    on EMP.HiringDate <= DS.[Date]  
        left join EmployeeInfoHistory as HIS
        on HIS.EmpId = EMP.EmpID and HIS.PromotionDate <= DS.[Date]  
option(MaxRecursion 10000)