Reputation: 247
I am looking for creating a SQL view where I have data as per the below screenshot
I want to convert rows into columns but based on # of Months. For Example, if # Month is 3 then add value to Jan, Feb, and Mar, and so on.
Upvotes: 0
Views: 206
Reputation: 739
The solution should look like this:
Create Table MonthDef (
MonthID int,
MonthAbbr varchar(3)
);
with SalaryMonthDetail as
(
select SalaryID, Salary, MonthAbbr from Salaries s inner join MonthDef m on s.months>=m.MonthID
)
select *
from SalaryMonthDetail
PIVOT(
Min(Salary)
FOR MonthAbbr IN (
[Jan],
[Feb],
[Mar],
[Apr],
[May],
[Jun],
[Jul],
[Aug],
[Sep],
[Oct],
[Nov],
[Dec]
)
) AS pivot_sal;
Upvotes: 1
Reputation: 88996
Something like this:
select ID
,case when Months >= 1 then Salary else null end Jan
,case when Months >= 2 then Salary else null end Feb
,case when Months >= 3 then Salary else null end Mar
,case when Months >= 4 then Salary else null end Apr
,case when Months >= 5 then Salary else null end May
from some_table
Upvotes: 1