我有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
一个人能够帮助我,我们提出了一个问题,但我现在从员工加入该组织那天获得了几个月的工资。我想要一个特定的年份让我们说2017年。
以下是查询:
; 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)
提前致谢。
答案 0 :(得分:0)
简而言之,我同意丹尼斯,但这是我的方法。它使用计数表instean消除了递归的需要。
IF ((SELECT OBJECT_ID('tempdb..#t')) IS NOT NULL)
DROP TABLE #t
IF ((SELECT OBJECT_ID('tempdb..#calendar')) IS NOT NULL)
DROP TABLE #calendar
SELECT TOP (25 *12) -- 25 years
IDENTITY(INT,0,1) AS N
INTO #T
FROM master.sys.all_columns ac1
CROSS JOIN master.sys.all_columns ac2
SELECT N
, [StartOfMonth] = DATEADD( MONTH, DATEDIFF( MONTH, 0, GETDATE())-n, 0)
, [Month] = DATENAME(MONTH, DATEADD( MONTH, DATEDIFF( MONTH, 0, GETDATE())-n, 0))
, [Year] = DATENAME(YEAR, DATEADD( MONTH, DATEDIFF( MONTH, 0, GETDATE())-n, 0))
, [EndOfMonth] = DATEADD( SECOND, -1, DATEADD( MONTH, DATEDIFF( MONTH, 0, GETDATE())-n+1, 0))
INTO #Calendar
FROM #T
SELECT e.EmpID,
c.StartOfMonth,
c.Month,
ISNULL(h.NewSalary, e.Salary) as Salary,
ISNULL(h.UpdatedEmployementStatus, e.EmployementStatus) as [Status]
FROM EmployeeInfo as e
INNER JOIN #Calendar c
ON e.HiringDate <= c.EndOfMonth
LEFT JOIN EmployeeInfoHistory as h
ON h.EmpId = e.EmpID
AND h.PromotionDate <= c.EndOfMonth
WHERE c.Year = 2017
ORDER BY e.empid, c.StartOfMonth