2017-07-25 133 views
0

我正在試圖獲得一個數據透視表,顯示該行最後的總數。這是可能的..但是,我無法得到它的工作。我有數據的數據,但我無法得到每行的總數。有沒有另外一種方法來完成這個?任何援助非常感謝。如何從數據透視表中獲得總計數

select sch.name, s.grade, s.schid, count(s.schid), 
     (select count(ss.schid) from students ss 
     where ss.enroll_status=0 
      and ss.schid = s.schid 
     group by ss.schid) as Total 
from students s 
inner join schools sch on 
s.schid = sch.schloc 
where s.enroll_status=0 
group by sch.name,s.grade, s.schid 
order by sch.name,s.schid, s.grade; 

這是它如何出現什麼

|School   |Grade |Loc  |Count |Total | 
|Amery Middle |7  |2740  |233 | 813 | 
|Amery Middle |8  |2740  |218 | 813 | 
|Porter Elem  |3  |12830 |2  | 68 | 
|Porter Elem  |4  |12830 |2  | 68 | 

這是怎麼需要出現在數據透視表:在學校中列有傲人的成績排顯示計數,然後總計跨越爲學校總招生

|    |count|count|count|count|count |count|Grand Total| 
|School   |3rd |4th |5th |6th |7th |8th |   | 
|Amery Middle |2 |2 |0 |0 |0  |0 |868  | 
|Porter Elem  |0 |0 |0 |0 |233 |218 |813  | 

感謝您提供的任何幫助。

回答

0

你可以這樣說:

SELECT NAME, 
     "Count 3rd", 
     "Count 4th", 
     "Count 5th", 
     "Count 6th", 
     "Count 7th", 
     "Count 8th", 
     "Count 3rd" + 
     "Count 4th" + 
     "Count 5th" + 
     "Count 6th" + 
     "Count 7th" + 
     "Count 8th" "Grand Total" 
FROM (SELECT sch.name, 
       s.grade, 
       s.schid 
     FROM students s 
       INNER JOIN schools sch ON s.schid = sch.schloc 
     WHERE s.enroll_status = 0) 
PIVOT (COUNT(*) FOR (grade) IN (3 AS "Count 3rd", 
           4 AS "Count 4th", 
           5 AS "Count 5th", 
           6 AS "Count 6th", 
           7 AS "Count 7th", 
           8 AS "Count 8th")); 

這假定總計列是學生的所有成績之和(即所有的學生都在一個檔次),所有牌號有已被選中。

+0

非常感謝你......這就像一個魅力! – teelee

+0

謝謝你的助手......你知道有沒有辦法選擇截然不同的東西?當我在兩個查詢中選擇「DISTINCT」時,都會刪除所有數據併爲每個成績列顯示「1」。我收到了一些重複項目,這些重複項目將計數關閉。感謝您給予的任何幫助! – teelee

+0

你可能會問這是一個新的問題,完整的數據和預期的輸出(就像你對這個問題所做的那樣 - 謝謝你,順便說一下)。 – Boneist