I have a table called tours in which I have following fields
tourId, tourStartDate, tourEndDate , tourDetail ,deptCode,targetYear, and officerName
Now i want to summarize my data into months
so result table should look like by following schema
declare @temp table (
id int identity(1,1) not null,
officerName,
jan int ,feb int,
march int,april int,
may int,
june int ,
july int,
aug int,
sep int,
oct int,
nov int,
dec int
);
select * from @temp
I tried with with cte to traverse each row and using case to insert in temporary table but its not look like good solution so any clue or guide really help me a lot.
count of tours done by officer in that month will appear in month column as value
EDITED
A tour with starting date in jan and ending date in some other month, say feb then its value will appear in both month
To make it appear in both months, UNION the query parts of (1) by start date (2) by end date, if end is in a different month. And to compare months, use MONTH to take the month of a date.
To get the column names as months, use DateName(Month, ). To make it consistent, use only the first 3 characters using LEFT.
To turn rows into columns, use PIVOT.