Monday, January 25, 2010

PIVOT


DECLARE @FromDate DATETIME
DECLARE @ToDate DATETIME

----------------
SET NOCOUNT ON

SET @FromDate = '10/1/2009'
SET @ToDate = '10/1/2010'

CREATE Table #tblSchool ( SchoolName VARCHAR(20), [Date] DATETIME, NoOfBoys INT, NoOfGirls INT )

DECLARE @SqlQuery VARCHAR(MAX)
DECLARE @Months VARCHAR(MAX)
DECLARE @DisplayMonths VARCHAR(MAX)
SET @SqlQuery = ''

INSERT INTO #tblSchool VALUES ('aa','1/1/2010', 10, 15)
INSERT INTO #tblSchool VALUES ('aa','1/2/2010', 15, 17)
INSERT INTO #tblSchool VALUES ('aa','2/1/2010', 18, 19)
INSERT INTO #tblSchool VALUES ('aa','2/2/2010', 21, 22)

INSERT INTO #tblSchool VALUES ('bb','1/1/2010', 11, 17)
INSERT INTO #tblSchool VALUES ('bb','1/2/2010', 16, 19)
INSERT INTO #tblSchool VALUES ('bb','2/1/2010', 19, 21)
INSERT INTO #tblSchool VALUES ('bb','2/2/2010', 25, 25)

;with MonthData AS
(
SELECT DATEADD(DD, 1 - DAY( @FromDate ), @FromDate ) AS MonthDates

UNION ALL

SELECT DATEADD(MM, 1, MonthDates ) AS MonthDates
FROM MonthData
WHERE MonthDates <= @ToDate
)

SELECT *
INTO #MonthData
FROM MonthData
ORDER BY MonthDates

SELECT @Months = STUFF(
(
SELECT ', [' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 1, 3 )
+ ' ' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 8, 4 )
+ ']'
FROM #MonthData
FOR XML PATH('')
),1,1,'')

SELECT @DisplayMonths = STUFF(
(
SELECT ', ISNULL( [' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 1, 3 )
+ ' ' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 8, 4 )
+ '], 0 ) AS [' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 1, 3 )
+ ' ' + SUBSTRING( CONVERT( VARCHAR(20), MonthDates ), 8, 4 )
+ ']'
FROM #MonthData
FOR XML PATH('')
),1,1,'')

SET @SqlQuery ='SELECT SchoolName, ' + @DisplayMonths + '
FROM
(
SELECT
SchoolName
, (
SUBSTRING( CONVERT( VARCHAR(20), [Date] ), 1, 3 )
+ '
' '' + SUBSTRING( CONVERT( VARCHAR(20), [Date] ), 8, 4 )
) AS BillMonth
, ( NoOfBoys + NoOfGirls ) AS TotalStudent
FROM #tblSchool
WHERE #tblSchool.[Date] BETWEEN '
'' + CAST( @FromDate AS VARCHAR(20) ) + ''' AND ''' + CAST( @ToDate AS VARCHAR(20) ) + '''
) AS ItemDetail
PIVOT ( SUM(TotalStudent) FOR BillMonth IN ( '
+ @Months + ' ) ) AS pvt '

PRINT ( @SqlQuery )
EXECUTE ( @SqlQuery )

DROP TABLE #tblSchool
DROP TABLE #MonthData

No comments: