下面是一个SQL Server Pivot Query,它提供如下输出:
Semester| StudentDesc | [A]| [B] |[C] |[D]
-----------------------------------------
| 2 | Term1 | 20 | NULL| 5 | 10
------------------------------------------
| 3 | Term2 | 10 | 2 | 2 | 1
-----------------------------------------
我希望输出包含A,B,C,D的总(TotalSessions),例如:
Semester| StudentDesc | [A]| [B] |[C] |[D] | TotalSessions
---------------------------------------------------------
| 2 | Term1 | 20 | NULL| 5 | 10 | 35
--------------------------------------------------------
| 3 | Term2 | 10 | 2 | 2 | 1 | 15
-------------------------------------------------------
我认为这将是名为的列 Count(Stats.SessionNumber)AS查询中的TotalSessions
我的查询是:
SELECT Semester, StudentDesc, [A],[B],[C],[D]
FROM
(
SELECT
Semesters.Semester, Options.StudentDesc,
/*TotalSessions */ Count(Stats.SessionNumber) AS
TotalSessions, TrainerList.ShortName
FROM Semesters, (StudentList_tbl
INNER JOIN
((RegistrarSemestersAndTerms
INNER JOIN
Stats ON (StudentSemestersAndTerms.Semester = Stats.Semester)
AND (StudentSemestersAndTerms.StudentID = Stats.StudentID))
INNER JOIN
Options ON StudentSemestersAndTerms.Q3 = Options.TermID)
ON StudentList_tbl.StudentID = StudentSemestersAndTerms.StudentID)
INNER JOIN
TrainerList ON StudentList_tbl.RTP = TrainerList.TrainerID
GROUP BY Semesters.Semester, Options.StudentDesc, TrainerList.ShortName
) as base_query
PIVOT
(
Sum(TotalSessions) FOR ShortName IN ([A],[B],[C],[D])
) as pivot_query;
感谢
答案 0 :(得分:1)
只需写作:
SELECT Semester, StudentDesc, [A],[B],[C],[D],
isnull([A],0)+isnull([B],0)+isnull([C],0)+isnull([D],0) as TotalSessions
FROM
--... rest of the query