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 Course
SELECT 1,'math 1' UNION ALL
SELECT 1,'phisisc 1' UNION ALL
SELECT 2,'math 1' UNION ALL
SELECT 3,'culture' UNION ALL
SELECT 3,'history' UNION ALL
SELECT 3,'art'
S_No course
----------- -------------------------
1 math 1
1 phisisc 1
2 math 1
3 culture
3 history
3 art
Then I want to get the result similar to:
s_no course 1 course 2 course 3
----------- ------------------------- ------------------------- ------------
1 math 1 phisisc 1 NULL
2 math 1 NULL NULL
3 art culture history
-- #1
if object_id('temp') is not null drop table temp
SELECT S_no,
course,
row=ROW_NUMBER() OVER(PARTITION BY S_no ORDER BY course)
INTO temp
FROM 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
-- #2
if object_id('temp') is not null drop table temp
SELECT S_no,
course,
row=ROW_NUMBER() OVER(PARTITION BY S_no ORDER BY course)
INTO temp
FROM 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.course
FROM
(
SELECT S_no,
course
FROM temp
WHERE row=1
) D1
FULL OUTER JOIN
(
SELECT S_no,
course
FROM temp
where row=2
)D2 ON D1.s_no=D2.S_no
FULL 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?