SQL Server Pivot Query添加总计

时间:2014-06-17 05:47:22

标签: sql sql-server

下面是一个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;

感谢

1 个答案:

答案 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