By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE #Students(
[Name] varchar(50),
[Surname] varchar(50),
[Period] int,
[Sport] int,
[History] int,
[English] int,
[Geography] int)
INSERT INTO
#Students([Name],[Surname],[Period],[Sport],[History],[English],[Geography])
VALUES
('Luke','Green',1,30,20,23,NULL),
('Mary','Brown',1,17,15,NULL,30),
('John','Red',1,18,NULL,21,30),
('Walter','White',1,22,20,5,30),
('John','Red',2,NULL,NULL,NULL,23);
5 rows affected
SELECT *
FROM #Students
Name | Surname | Period | Sport | History | English | Geography |
---|---|---|---|---|---|---|
Luke | Green | 1 | 30 | 20 | 23 | null |
Mary | Brown | 1 | 17 | 15 | null | 30 |
John | Red | 1 | 18 | null | 21 | 30 |
Walter | White | 1 | 22 | 20 | 5 | 30 |
John | Red | 2 | null | null | null | 23 |
SELECT Name, Surname, Sbj, Mark
FROM #Students
UNPIVOT
(
Mark
for Sbj in ([Sport],[History],[English],[Geography])
) u
WHERE Period=1
Name | Surname | Sbj | Mark |
---|---|---|---|
Luke | Green | Sport | 30 |
Luke | Green | History | 20 |
Luke | Green | English | 23 |
Mary | Brown | Sport | 17 |
Mary | Brown | History | 15 |
Mary | Brown | Geography | 30 |
John | Red | Sport | 18 |
John | Red | English | 21 |
John | Red | Geography | 30 |
Walter | White | Sport | 22 |
Walter | White | History | 20 |
Walter | White | English | 5 |
Walter | White | Geography | 30 |