I have written a SQL query that fills the following columns in a temporary table:
CODE | MODULE | MONTH | YEAR | SO_NUM | LABOR_HRS | LABOR_COST
From this table, I need to create a select statement that returns the same data, split up by month, like so:
CODE | MODULE | SO_NUM_MONTH1 | LABOR_HRS_MONTH1 | LABOR_COST_MONTH1 | SO_NUM_MONTH2 | LABOR_HRS_MONTH2 | LABOR_COST_MONTH2 | etc...
Code and module do not vary with month, as you can see. There will always be six months worth of data in the temporary table. However, what gets me is that the month does not always start at 1 (month and year are integers).
I also would like the resulting columns to be named based on the month and year, so in the above example, assuming that the data starting in January 2011, the names might be:
CODE | MODULE | SO_NUM_JAN_2011 | LABOR_HRS_JAN_2011 | LABOR_COST_JAN_2011 | SO_NUM_FEB_2011 | LABOR_HRS_FEB_2011 | LABOR_COST_FEB_2011 | etc...
This project is being developed in SQL Server 2008 R2.
Here’s some code to get you started. Basically, it creates a table with the fields that you need and you can just drop it and recreate it as necessary. You’ll need to finish adding the rest of the fields to the dynamic SQL part (@CreateTable), and then you’ll need to build some insert and update queries to populate it. I’d use some dynamic sql like what I used to create the table to do those so you get the field names from the variables.