SQL Server 2000 を使用しているため、PIVOT
関数がないため、集計関数とCASE
ステートメントを使用してこれを複製する必要があります。これに似ています:
select employeeid,
sum(case when DatePart(Month, EffectiveDate) = 1 then Salary end) as Jan,
sum(case when DatePart(Month, EffectiveDate) = 2 then Salary end) as Feb,
sum(case when DatePart(Month, EffectiveDate) = 3 then Salary end) as Mar,
sum(case when DatePart(Month, EffectiveDate) = 4 then Salary end) as Apr,
sum(case when DatePart(Month, EffectiveDate) = 5 then Salary end) as May,
sum(case when DatePart(Month, EffectiveDate) = 6 then Salary end) as Jun,
sum(case when DatePart(Month, EffectiveDate) = 7 then Salary end) as Jul,
sum(case when DatePart(Month, EffectiveDate) = 8 then Salary end) as Aug,
sum(case when DatePart(Month, EffectiveDate) = 9 then Salary end) as Sep,
sum(case when DatePart(Month, EffectiveDate) = 10 then Salary end) as Oct,
sum(case when DatePart(Month, EffectiveDate) = 11 then Salary end) as Nov,
sum(case when DatePart(Month, EffectiveDate) = 12 then Salary end) as Dec
from yourtable
group by employeeid
デモで SQL Fiddle を参照してください
上記のコメントに基づいて、ある月から次の月に値を持ち越すことに基づいて編集してください。
declare @query as nvarchar(max) = '',
@rowcount as int = 1,
@pivotrow as int,
@currentMonthSalary as int = 0,
@priorMonthSalary as int = 0,
@employeeid int
select distinct effectivedate
into #colspivot
from yourtable
while @rowcount <= 12 -- loop thru each month
begin
set @pivotrow = (select top 1 datepart(month, effectivedate)
from #colspivot
order by datepart(month, effectivedate))
select @currentMonthSalary = salary, @employeeid = EmployeeID
from yourtable
where datepart(month, effectivedate) = @pivotrow
if @pivotrow = @rowcount
begin
insert into FinalData (employeeid, effectivemonth, salary)
select @employeeid, cast(DateName(month, DateAdd(month, @pivotrow, 0) -1) as varchar(3)), @currentMonthSalary
set @query = @query + ', sum(case when effectivemonth = ''' + cast(DateName(month, DateAdd(month, @pivotrow, 0) -1) as varchar(3)) + '''
then ' + cast(@currentMonthSalary as varchar(10)) + ' end) as '+ cast(DateName(month, DateAdd(month, @pivotrow, 0) -1) as varchar(3))
delete from #colsPivot where datepart(month, effectivedate) = @pivotRow
set @priorMonthSalary = @currentMonthSalary
end
else
begin
insert into FinalData (employeeid, effectivemonth, salary)
select @employeeid, cast(DateName(month, DateAdd(month, @rowcount, 0) -1) as varchar(3)), @priorMonthSalary
set @query = @query + ', sum(case when effectivemonth = ''' + cast(DateName(month, DateAdd(month, @rowcount, 0) -1) as varchar(3)) + '''
then ' + cast(@priorMonthSalary as varchar(10)) + ' end) as '+cast(DateName(month, DateAdd(month, @rowcount, 0) -1) as varchar(3))
end
if @rowcount <= 12
set @rowcount = @rowcount + 1
end
set @query = 'select employeeid '+ @query
+ ' from FinalData group by employeeid;'
exec(@query)
SQL Fiddle with Demoを参照してください。FinalData
SQL ステートメントの作成をループしながら、毎月のデータを格納 する新しいテーブルを作成しました。