簡體   English   中英

SQL Server數據透視查詢添加總計

[英]SQL Server Pivot Query add a total

您好,下面是一個SQL Server Pivot查詢,其輸出如下:

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;

謝謝

簡單地寫為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM