可以使用PIVOT
表操作要做到這一點,是這樣的:
WITH CTE
AS
(
SELECT
k.name as firstname,
k.surname as lastname,
k.Email,
c.CourseName, c.CourseID
FROM Students k
JOIN StudentCourses dn ON dn.StudentID = k.StudentID
INNER JOIN Courses c ON dn.CourseID = c.CourseID
WHERE c.CourseName IN ('Course1','Course2','Course3')
)
SELECT *
FROM CTE AS c
PIVOT
(
MAX(CourseID)
FOR CourseName IN ([Course1], [Course2], [Course3])
) u;
需要注意的是,既然你沒有其他在每個學生的每個欄目下顯示的列,此查詢將顯示CourseID
VA如果學生沒有這門課程,則爲每個課程名稱提供。你應該選擇以顯示更多相應的列,而不是像馬克例如:
WITH CTE
AS
(
SELECT
k.name as firstname,
k.surname as lastname,
k.Email,
c.CourseName, dn.Mark
FROM Students k
JOIN StudentCourses dn ON dn.StudentID = k.StudentID
INNER JOIN Courses c ON dn.CourseID = c.CourseID
WHERE c.CourseName IN ('Course1','Course2','Course3')
)
SELECT *
FROM CTE AS c
PIVOT
(
MAX(Mark)
FOR CourseName IN ([Course1], [Course2], [Course3])
) u;
這會給你:
| firstname | lastname | Email | Course1 | Course2 | Course3 |
|-----------|----------|-------|---------|---------|---------|
| StudentA | test | test | 19 | 20 | 15 |
| StudentB | test | test | 16 | 17 | 20 |
| StudentC | test | test | 20 | 19 | 15 |
還要注意的是,你應該仔細查看您在錨點查詢中選擇的列:
...
SELECT
k.name as firstname,
k.surname as lastname,
k.Email,
c.CourseName, dn.Mark
...
因爲PIVOT
表運營商將通過組除了你列出,並用樞列的所有列:
MAX(CourseID)
FOR CourseName IN
所以你的情況,它會按firstname, lastname, Email
。
使用PIVOT/UNPIVOT運算符,你可以拉只有一個學生,當然列行和使用操作員轉置數據 – Charleh
或拋出一些示例數據(無圖像)a並輸出願望 – KumarHarsh
假設您只有3個課程,我已硬編碼的情況下,否則查詢需要更改
SELECT k.name as firstname, k.surname as lastname, k.Email, Case when dn.CourseName ='Course1' then 'Course1' else '-' end AS Course1, Case when dn.CourseName ='Course2' then 'Course2' else '-' end AS Course2, Case when dn.CourseName ='Course3' then 'Course3' else '-' end AS Course3, FROM Students k JOIN StudentCourses dn ON dn.StudentID = k.StudentID Join CourseId AS ci on dn.CourseId = ci.id
– Sumant