Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Crosstab Query

$
0
0

Hi,  I am trying to replicate an access crosstab query
I have use PIVOT but this is not working as this requires an aggregate function.

However , I would like output in this format:

ClassHistoryMathsArt
Class1Student1Student2Student1
Class1Student5Student6Student4
Class1Student6Student6

A
ny thoughts ?

DECLARE @School TABLE (Class VARCHAR(10), [Subject] VARCHAR(20), Student VARCHAR(20))

 INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','History','Student1')
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','History','Student5')
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','History','Student6')
 
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','Maths','Student2')
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','Maths','Student6')
 
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','Art','Student1')
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','Art','Student4')
INSERT INTO @School(Class, [Subject], Student)  VALUES('Class1','Art','Student6')
 
  -- Pivot table
SELECT Class,
[History], [Maths], [Art]
FROM
(SELECT Class, [Subject], Student
    FROM @School) AS tbl
PIVOT(Min(Student) FOR [Subject] IN ([History], [Maths], [Art])) As pvt


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>