Created
October 14, 2014 11:07
-
-
Save niisar/ab1694128935354aac39 to your computer and use it in GitHub Desktop.
xml path tut 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create table | |
CREATE TABLE #TestTable (StudentName VARCHAR(100), Course VARCHAR(100), Instructor VARCHAR(100), RoomNo VARCHAR(100)) | |
GO | |
-- Populate table | |
INSERT INTO #TestTable (StudentName, Course, Instructor, RoomNo) | |
SELECT 'Mark', 'Algebra', 'Dr. James', '101' | |
UNION ALL | |
SELECT 'Mark', 'Maths', 'Dr. Jones', '201' | |
UNION ALL | |
SELECT 'Joe', 'Algebra', 'Dr. James', '101' | |
UNION ALL | |
SELECT 'Joe', 'Science', 'Dr. Ross', '301' | |
UNION ALL | |
SELECT 'Joe', 'Geography', 'Dr. Lisa', '401' | |
UNION ALL | |
SELECT 'Jenny', 'Algebra', 'Dr. James', '101' | |
GO | |
-- Check orginal data | |
SELECT * | |
FROM #TestTable | |
GO | |
-- Group by Data using column and XML PATH | |
SELECT | |
StudentName, | |
STUFF(( | |
SELECT ', ' + Course + ' by ' + CAST(Instructor AS VARCHAR(MAX)) + ' in Room No ' + CAST(RoomNo AS VARCHAR(MAX)) | |
FROM #TestTable | |
WHERE (StudentName = StudentCourses.StudentName) | |
FOR XML PATH ('')) | |
,1,2,'') AS NameValues | |
FROM #TestTable StudentCourses | |
GROUP BY StudentName | |
GO | |
-- Clean up | |
DROP TABLE #TestTable | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment