oracle - 使用不同的值汇总具有值组的表

时间:2017-01-06 18:45:19

标签: sql oracle group-by

我有这样的表:

school    grade     type      
------    -----     -----
sc1        g1        t1
sc2        g2        t1
sc3        g4        t3
sc4        g3        t2
sc1        g2        t3

...等

  • 柱级具有4个不同的值g1,g2,g3,g4
  • 列类型具有3个不同的值t1,t2,t3
  • 专栏学校有120个不同的价值

并且我会像这张表一样得到摘要:(对于每个不同的专栏1 - 学校 - )

school g1    g2   g3    g4    sum(g1+g2+g3+g4)   t1  t2  t3 sum(t1+t2+t3)
sc1      3    5     1     1             10        21  4   2       27
sc2      2    4     5     5             16        5   23  1       29

等...

如何编写此查询以通过使用报表生成器V6i

为我提供所需的结果?
  • 我获得了所有数量的不同学校的第一级并命令他们升序
  • 我查询每个值(g1,g2,g3,g4,t1,t2,t3) 我想在不使用报告
  • 的情况下在sql查询中获取该表

1 个答案:

答案 0 :(得分:0)

条件聚合:

with
     like_this ( school, grade, typ ) as (
       select 'sc1', 'g1', 't1' from dual union all
       select 'sc2', 'g2', 't1' from dual union all
       select 'sc3', 'g4', 't3' from dual union all
       select 'sc4', 'g3', 't2' from dual union all
       select 'sc1', 'g2', 't3' from dual
     )
-- end of test data; SQL query begins below this line
select school,
       count(case when grade = 'g1' then 1 end) as g1,
       count(case when grade = 'g2' then 1 end) as g2,
       count(case when grade = 'g3' then 1 end) as g3,
       count(case when grade = 'g4' then 1 end) as g4,
       count(grade)                             as total_g,
       count(case when grade = 't1' then 1 end) as t1,
       count(case when grade = 't2' then 1 end) as t2,
       count(case when grade = 't3' then 1 end) as t3,
       count(typ)                               as total_t
from   like_this
group by school
order by school  --  optional
;

SCH      G1      G2      G3      G4 TOTAL_G      T1      T2      T3 TOTAL_T
--- ------- ------- ------- ------- ------- ------- ------- ------- -------
sc1       1       1       0       0       2       0       0       0       2
sc2       0       1       0       0       1       0       0       0       1
sc3       0       0       0       1       1       0       0       0       1
sc4       0       0       1       0       1       0       0       0       1

4 rows selected.