Skip to content Skip to sidebar Skip to footer

Iterate Within View In Sql Server

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

Solution 1:

Something like this:

select ID
       ,casewhen Months >=1then Salary elsenullend Jan
       ,casewhen Months >=2then Salary elsenullend Feb
       ,casewhen Months >=3then Salary elsenullend Mar
       ,casewhen Months >=4then Salary elsenullend Apr
       ,casewhen Months >=5then Salary elsenullend May
from some_table

Solution 2:

The solution should look like this:

  1. First create a table or function to return your cross reference of Months to their abbreviations. Going simple, it looks like:
CreateTable MonthDef (
  MonthID int,
  MonthAbbr varchar(3)
);
  1. Join the table above with your salary to convert your salary data to have month detail granularity
with SalaryMonthDetail as
(
 select SalaryID, Salary, MonthAbbr from Salaries s inner join MonthDef m on s.months>=m.MonthID
)
  1. Pivot the result and convert those rows to columns
select *
from SalaryMonthDetail
PIVOT(
    Min(Salary) 
    FOR MonthAbbr IN (
        [Jan], 
        [Feb], 
        [Mar], 
        [Apr], 
        [May], 
        [Jun], 
        [Jul],
        [Aug],
        [Sep],
        [Oct],
        [Nov],
        [Dec]
    )
) AS pivot_sal;
  1. Put 2 to 3 in a view and select like seen here

Post a Comment for "Iterate Within View In Sql Server"