27 Sept 2011

Pivot Table in SQL Server

I have a data like this:

Employee No Training Date
C11 .Net 1/1/2008
C11 Java 1/2/2008
C11 SQL Server 1/3/2008
C12 .Net 1/4/2008
C12 Java 1/5/2008
C13 SQL Server 1/6/2008

Would like the output like this:

Employee No Training Date Training Date Training Date
C11 .Net 1/1/2008 Java 1/2/2008 SQL Server 1/3/2008
C12 .Net 1/4/2008 Java 1/5/2008    
C13 SQL Server 1/6/2008        

One Employee can have n number of Trainings.

Code Snippet
Create TABLE #Table
(EmployeeID int,
Training varchar(50),
DTE datetime)
INSERT INTO #Table Values(11,'.Net', '1/1/2008')
INSERT INTO #Table Values(11,'Java', '1/2/2008')
INSERT INTO #Table Values(11,'SQL', '1/3/2008')
INSERT INTO #Table Values(12,'.Net', '1/4/2008')
INSERT INTO #Table Values(12,'Java', '1/5/2008')
INSERT INTO #Table Values(13,'SQL', '1/6/2008')

DECLARE @listCol VARCHAR(2000)
SELECT @listCol = STUFF(( SELECT DISTINCT
'],[' + ltrim(Training)
FROM #Table
ORDER BY '],[' + ltrim(Training)
FOR XML PATH('')
), 1, 2, '') + ']'

Print @listCol

DECLARE @query VARCHAR(4000)
SET @query =
'SELECT * FROM
(SELECT EmployeeID, Training
FROM #Table
) src
PIVOT (max(Training) FOR Training
IN ('+@listCol+')) AS pvt'
print @query
EXECUTE (@query)

DECLARE @query2 VARCHAR(4000)
SET @query2 =
'SELECT * FROM
(SELECT EmployeeID, Training, DTE
FROM #Table
) src
PIVOT (max(DTE) FOR Training
IN ('+@listCol+')) AS pvt'
print @query2
EXECUTE (@query2)


DECLARE @query3 VARCHAR(4000)
SET @query3 =
'SELECT * FROM (
SELECT * FROM
(SELECT EmployeeID, Training
FROM #Table
) src
PIVOT (max(Training) FOR Training
IN ('+@listCol+')) AS pvt
) A
JOIN
(
SELECT * FROM
(SELECT EmployeeID, Training, DTE
FROM #Table
) src
PIVOT (max(DTE) FOR Training
IN ('+@listCol+')) AS pvt
) B
ON A.EmployeeID = B.EmployeeID
'
print @query3
EXECUTE (@query3)

No comments:

Post a Comment