I’m sure this won’t be a difficult question for the hardcore SQL geeks, but I need some help. This is for SQL Server 2000 (inherited projects!).
I have a table of salary listings that look like this:
EmployeeID | EffectiveDate | Salary
1 | 2/1/2011 | 500
1 | 6/1/2011 | 600
1 | 12/1/2011 | 650
I need to create a query that will output these salaries by month for a given year. So the output would be like
EmployeeID | Jan | Feb | Mar | Apr | Apr | May | Jun | Jul | Aug | Sept | Oct | Nov | Dec
1 | 500 | 500 | 500 | 500 | 500 | 500 | 600 | 600 | 600 | 600 | 600 | 600 | 650
I know there must be a way to do this effectively with SQL, I just can’t seem to get it right. Obviously, I would be naming the month columns above with SQL such as
SELECT EmployeeID, ‘Jan’ AS Jan, ‘Feb’ AS Feb, etc but the rest of the statement is harder since I’m looking for ranges.
Since you are using SQL Server 2000 it does not have a
PIVOTfunction, so you will have to replicate this using an aggregate function and aCASEstatement. Similar to this:See SQL Fiddle with Demo
Edit, based on your comments above carrying over the value from one month to the next, here is a solution that might work for you.
See SQL Fiddle with Demo. I created a new table
FinalDatato store the data for each month while I loop through creating the sql statement.