This is the first time I am trying to pivot a table. I have managed to pivot the table with only one measure and failed to do it with multiple measures. Please can I get some advice? Below is the test data I have and I would like to see. Please note that I have around 20 to 30 measures.
Thanks in advance!
-- Test Data HAVE
CREATE TABLE #have
(Name VARCHAR(50),Subject Varchar(20), Marks1 INT,Marks2 INT, Result Varchar(20) )
GO
INSERT INTO #have VALUES('Jsmith','Maths',65,56,'Pass')
INSERT INTO #have VALUES('Jsmith','Science',42,72,'Failed')
GO
-- Test Data WANT
CREATE TABLE #want
(Name VARCHAR(50),Maths_Marks1 INT ,Maths_Marks2 INT,Science_Marks1 INT,Science_Marks2 INT, Maths_Result Varchar(20), Science_Result Varchar(20))
GO
INSERT INTO #want VALUES('Jsmith',65,56,42,72,'Pass','Failed')
GO
select * from #have
select * from #want
-- Pivot table
SELECT Name , [Maths] AS [Maths_Marks1], [Science] AS [Science_Marks1]
FROM
(SELECT Name, Subject, Marks1 FROM #have) as SourceTable
PIVOT
(SUM(Marks1)
FOR Subject in ([Maths],[Science])
) as PivotTable1
-- Also Tried..Unable to get it working
SELECT Name , [Maths] AS [Maths_Marks1], [Science] AS [Science_Marks1]
FROM
(SELECT Name, Subject, Marks1 FROM #have) as SourceTable
PIVOT
(SUM(Marks1)
FOR Subject in ([Maths])
) as PivotTable1
(SELECT Name, Subject, Marks2 FROM #have) as SourceTable
PIVOT
(SUM(Marks2)
FOR Subject in ([Science])
) as PivotTable2
This trick builds on Marks properties : they are integers , mark <1000, exactly 2 marks columns (Marks1, Marks2) are in the table.
Otherwise , generally do it with conditional aggregates