我有2个表[EmployeeInfo]
[EmployeeInfoHistory]
,我在此表中存储员工的工资。我能够得到员工的工资与员工和员工的薪水。
但我想显示每个月的员工工资,如下所示。
我的结构是[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
);
信息表数据:
EmpID Salary Status HiringDate
1 20000 Intern 2017-10-02
2 30000 Jr. DBA 2017-11-01
InfoHistory表的数据:
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
提前致谢
答案 0 :(得分:0)
获取历史记录表中sum
列数据的salary
与所需员工ID对应的月份。
答案 1 :(得分:0)
您需要一张包含日期的表格。在这里,我使用CTE制作了一张桌子,我加入你的桌子。
; 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)