August 28, 2013 at 12:56 pm
The query below brings back the sum of course hours grouped by week. The issue is, the week values can be different every time they can not be defined in the query. Here is an example of what is brought back in the query:
ID Category Week of Total Hours
1111554 Case Management 7/2/2012 7
1111554 Case Management 7/9/2012 7
1111554 Case Management 7/16/2012 7
1111554 Pre-GED 7/2/2012 3
1111554 Pre-GED 7/9/2012 3
1111554 Pre-GED 7/16/2012 3
QUERY
WITH cteSource(DOP_ID, Category, WeekOf, [Hours])
AS (
SELECT DOP_ID,
Category,
DATEADD(DAY, DATEDIFF(DAY, '19000101', [Date]) / 7 * 7 , '19000101') AS WeekOf, -- Monday
[Hours]
FROM GW_PPP.dbo.SLAM_Attendence
)
SELECT DOP_ID AS ID,
Category,
WeekOf AS [Week of],
SUM([Hours]) AS [Total Hours]
FROM cteSource
GROUP BY DOP_ID,
Category,
WeekOf
ORDER BY DOP_ID,
Category,
WeekOf;
Again, I can't figure out how to Pivot the table by not defining the weeks in the query
SO not using something like this where the week of is defined:
pivot
(
week of in ([7/2/2012], [7/9/2012],
[7/16/2012 ])
) piv
I would also like to add a sum column by month if possible. Here is the output I would like:
ID Category 7/2/2012 7/9/2012 7/16/2012 July 12 Total
1111554 Case Management 7 7 7 21
1111554 Pre-GED 3 3 3 12
August 28, 2013 at 1:45 pm
You can use a crosstab instead of a PIVOT. This will offer the ability to make it dynamic too. Take a look at the links in my signature about cross tabs, specifically the second one. It should be the method you are looking for.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
September 20, 2013 at 1:15 am
CREATE TABLE [dbo].[gotilla](
[ID] [int] NULL,
[Category] [varchar](50) NULL,
[Weekof] [varchar](50) NULL,
[Total_hur] [int] NULL
)
select category ,id,Sum(case when weekof='7/2/2012'then total_hur end)as '7/2/2012',
SUM(case when weekof='7/16/2012'then total_hur end)as '7/16/2012',
SUM(case when weekof='7/9/2012'then total_hur end)as '7/9/2012'
from gotilla
group by category,id
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply