Hi all,I would like to learn more in T-SQL Querying to this reason I want you to help me to create more solutions.I have one table with structure and instances under:CREATE TABLE Course( S_No int, course nvarchar(25) ) INSERT CourseSELECT 1,'math 1' UNION ALLSELECT 1,'phisisc 1' UNION ALLSELECT 2,'math 1' UNION ALLSELECT 3,'culture' UNION ALLSELECT 3,'history' UNION ALLSELECT 3,'art'S_No course----------- -------------------------1 math 11 phisisc 12 math 13 culture3 history3 art
Then I want to get the result similar to:s_no course 1 course 2 course 3----------- ------------------------- ------------------------- ------------1 math 1 phisisc 1 NULL2 math 1 NULL NULL3 art culture history-- #1if object_id('temp') is not null drop table tempSELECT S_no, course, row=ROW_NUMBER() OVER(PARTITION BY S_no ORDER BY course) INTO tempFROM Course SELECT s_no, [course 1]=(SELECT course FROM temp t WHERE t.s_no=s.s_no AND t.row=1), [course 2]=(SELECT course FROM temp t WHERE t.s_no=s.s_no AND t.row=2), [course 3]=(SELECT course FROM temp t WHERE t.s_no=s.s_no AND t.row=3)FROM (SELECT DISTINCT s_no FROM temp) s-- #2if object_id('temp') is not null drop table tempSELECT S_no, course, row=ROW_NUMBER() OVER(PARTITION BY S_no ORDER BY course) INTO tempFROM Course SELECT [Student Number]=(CASE WHEN D1.S_no IS NOT NULL THEN D1.S_no ELSE CASE WHEN D2.S_no IS NOT NULL THEN D2.S_no ELSE D3.S_no END END), D1.course, D2.course, D3.courseFROM( SELECT S_no, course FROM temp WHERE row=1) D1FULL OUTER JOIN ( SELECT S_no, course FROM temp where row=2)D2 ON D1.s_no=D2.S_noFULL OUTER JOIN( SELECT S_no, course FROM temp WHERE row=3)D3 ON D3.s_no=D2.S_no
Please post other correct queries.And can be the columns in a query variable?