我有表A
id    product_type      product_kind
1          图书             科技
2          图书             宗教
3          其它             杂志
4          录像             科技
5          录音             教育
6          图书             科技
7          图书             科技
8          图书             宗教
9          其它             杂志
10         录像            科技
11         录音             教育
12         图书             科技
13         录像            相声
......product_type是父类,product_kind是子类,有没有方法可以统计处如下结果:
图书      科技     4
图书      宗教     2
图书      (空)   6录音      教育     2
录音      (空)   2录像      科技     2
录像      相声     1
录像      (空)   3其它      杂志     2
其它      (空)   2(行之间的空是不要的,是为了大家看个清楚!)
或者是类似的统计方法,我就是要知道每小类的合计,同时还要知道大类的合计,最好能用一个SQL就查出来。
帮帮忙,我能等到10点钟。

解决方案 »

  1.   

    另外,如果空不要的话,简单很多。select product_type,product_kind,count(*) from a
    group by product_type,product_kind;还是要说句,如果是父子结构,要么标志上层节点ID,要么分表。
    得罪之处,多多海涵。
      

  2.   

    with a as(
      select 1  id,'图书' product_type,'科技' kind from dual union all   
      select 2  id,'图书' product_type,'宗教' kind from dual union all   
      select 3  id,'其它' product_type,'杂志' kind from dual union all   
      select 4  id,'录像' product_type,'科技' kind from dual union all   
      select 5  id,'录音' product_type,'教育' kind from dual union all   
      select 6  id,'图书' product_type,'科技' kind from dual union all   
      select 7  id,'图书' product_type,'科技' kind from dual union all   
      select 8  id,'图书' product_type,'宗教' kind from dual union all   
      select 9  id,'其它' product_type,'杂志' kind from dual union all   
      select 10 id,'录像' product_type,'科技' kind from dual union all   
      select 11 id,'录音' product_type,'教育' kind from dual union all   
      select 12 id,'图书' product_type,'科技' kind from dual union all   
      select 13 id,'录像' product_type,'相声' kind from dual
    )
    select product_type,decode(grouping(kind),0,kind)kind,count(1)
    from a
    group by grouping sets((product_type,kind),(product_type))
      

  3.   

    这里decode(grouping(kind),0,kind)kind直接写成kind也可以
      

  4.   

    SORRY,我理解失误,你只是说行之间的空行不要。
    那么,应该是:select a.product_type,product_kind,total from
    (select product_type,product_kind,count(*) total from a 
    group by product_type,product_kind)
    union
    (select product_type,'' product_kind,count(*) total from a 
    group by product_type,'');
      

  5.   

    select * from
    (select product_type,product_kind,count(*) from a
    group by product_type,product_kind
    union all
    select product_type,null as product_kind,count(*) from a
    group by product_type
    ) order by product_type,product_kind nulls last
      

  6.   

    我看见了,你的意思,我完全明白。不过,我弱弱说声:如果你考虑另一种设计,统计会方便很多。
    上面SQL有误,SORRY,没有测试环境。
    其实数据库设计,不仅是为了查询,更多为了报表。有些设计,可以为了报表而不遵守范式。
      

  7.   

    真是谢谢各位了。
    suiziguo 说的对,刚开始接触数据库的时候确实是认为数据是用来做数据存储以及查询用的。慢慢的才发现所有基于数据库的系统,最终结果都是出统计报表。
    可惜这个库不是我设计的。
    更可惜的是如果知道能这么快解决我就多给点分了,真是对不住各位了。