表
财政年度:2014年4月1日至2015年3月1日
Employee Effective Date Basic Salary
Freddy 2012-Apr-01 1000
Ann 2013-Apr-01 900
John 2014-Mar-01 1000
Ann 2014-Aug-01 1200
John 2014-Oct-01 1500
Freddy 2014-Oct-01 2000
John 2015-Jan-01 3000
Freddy 2015-Mar-01 2500
输出:
财政年度:2014年4月1日至2015年3月1日
Name | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | Jan | Feb | Mar
Freddy 1000 1000 1000 1000 1000 1000 2000 2000 2000 2000 2000 2500
Ann 900 900 900 900 1200 1200 1200 1200 1200 1200 1200 1200
John 1000 1000 1000 1000 1000 1000 1500 1500 1500 3000 3000 3000
答案 0 :(得分:3)
我首先创建您的数据:
declare @table table(Employee varchar(10), Effective_Date date, Basic_Salary int);
Insert into @table(Employee, Effective_Date, Basic_Salary) values
('Freddy', '2012-April-01', 1000)
, ('Ann', '2013-April-01', 900)
, ('John', '2014-Mar-01', 1000)
, ('Ann', '2014-Aug-01', 1200)
, ('John', '2014-Oct-01', 1500)
, ('Freddy', '2014-Oct-01', 2000)
, ('John', '2015-Jan-01', 3000)
, ('Freddy', '2015-Mar-01', 2500);
这是您的财政年度的开始:
Declare @startDate date = '2014-April-01';
主要查询:
With finYears(finY) as (
Select DATEADD(month, n, @startDAte) From (values(0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) as x(n)
)
Select * From (
Select e.Employee, name = Left(DATENAME(month, f.finY), 3), t.Basic_Salary
From finYears f
Cross Join (Select distinct Employee From @table) as e
Cross Apply (Select MAX(Effective_Date) From @table x Where x.Effective_Date <= f.finY and x.Employee = e.Employee) mx(maxYear)
Inner Join @table t on t.Employee = e.Employee and t.Effective_Date = mx.maxYear
) as p
Pivot(
sum(Basic_Salary)
for name in ([Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec], [Jan], [Feb], [Mar])
) as piv
一旦数据准备就绪并且每个员工每个月都有一份工资,它就会将表格调整为12个月。
输出:
Employee Apr May Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar
Ann 900 900 900 900 1200 1200 1200 1200 1200 1200 1200 1200
Freddy 1000 1000 1000 1000 1000 1000 2000 2000 2000 2000 2000 2500
John 1000 1000 1000 1000 1000 1000 1500 1500 1500 3000 3000 3000