如何从数据透视表中获取总计

时间:2017-07-25 14:46:09

标签: oracle

我正在尝试获取一个数据透视表,显示该行末尾的总计。这是可能的......但是,我无法让它工作。我有计数数据,但我不能得到每一行的总数。还有另一种方法来实现这一目标吗?非常感谢任何帮助。

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        |

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分: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"));

这假设总总栏数是所有年级学生的总和(即所有学生都在一个年级)并且所有成绩都已被选中。