Possible Duplicate:
How to group by the each week upto last six week sundays dates in sql?
I need to take the count of weekno. It works fine but i don’t know the weekno that is [34],[35],[36],[37],[38],[39]. The weekno knows only on the runtime.For example in a year it contains totally 52 weeks. I got this query from the help of @Bluefeet, he posted the query on the same stackoverflow. If i change the from date and to date in the between field it doesn’t work. Because i hard coded the weekno in the below query. Please give me the solution whatever the date in the between field within the year.
SET DATEFIRST 1
SELECT case when InstanceType is not null then InstanceType else 'Sum' End InstanceType ,
sum([34]) AS FirstWeek,
sum([35]) AS SecondWeek,
sum([36]) AS ThirdWeek,
sum([37]) AS FourthWeek,
sum([38]) AS FifthWeek,
sum([39]) AS SixthWeek,
max(InstanceDescription) AS InstanceDescription
FROM
(
SELECT [SPGI01_INSTANCE_TYPE_C] AS InstanceType,
[34], [35], [36], [37], [38], [39], InstanceDescription
FROM
(
SELECT I01.[SPGI01_INSTANCE_TYPE_C],
DatePart(wk, I01.[SPGI01_CREATE_S]) WeekNo,
DATEADD(DAY, 7 -DATEPART(WEEKDAY,I01.[SPGI01_CREATE_S]), I01.[SPGI01_CREATE_S]) WeekEnd,
J03.SPGJ03_MSG_TRANSLN_X InstanceDescription
FROM [SUPER-G].[dbo].[CSPGI01_ASN_ACCURACY] I01
INNER JOIN [SUPER-G].[dbo].[CSPGI50_VALID_INSTANCE_TYPE] I50
ON I50.[SPGI50_INSTANCE_TYPE_C] = I01.[SPGI01_INSTANCE_TYPE_C]
LEFT JOIN CSPGJ02_MSG_OBJ J02
ON I50.SPGJ02_MSG_K = J02.SPGJ02_MSG_K
LEFT JOIN CSPGJ03_MSG_TRANSLN J03
ON J02.SPGJ02_MSG_K = J03.SPGJ02_MSG_K
where I50.[SPGA04_RATING_ELEMENT_D] = 1
and I01.[SPGI01_EXCEPTIONED_F] = 'N'
and I01.[SPGI01_DISPUTED_F] != 'Y'
AND J03.[SPGJ03_LOCALE_C] = 'en_US'
and I01.[SPGA02_BUSINESS_TYPE_C] = 'PROD'
and I01.[SPGA03_REGION_C] = 'EU'
and I01.[SPGI01_SUB_BUSINESS_TYPE_C] = 'PRD'
and I01.[SPGI01_CREATE_S] between '10-08-2012 00:00:00.000' AND '11-18-2012 23:59:59.000'
) x
pivot
(
count(WeekEnd)
FOR weekno IN ([34], [35], [36], [37], [38], [39])
) p
) x1
GROUP BY InstanceType WITH ROLLUP
If you are looking to be able to pass in any date values to get the data that meets your criteria, then for this type of
PIVOTyou will need to use a dynamic SQL solution similar to this:Note: this is untested since I do not have any sample data, etc.