有一张表(T),其中关键列如下:
姓名 
A
B
A
B
A
C
C
A然后我做了一个分类统计:select 姓名,
(case when 姓名=‘A’ then count(*)
when 姓名=‘B’ then count(*)
when 姓名=‘C’ then count(*)
end) 次数
from T姓名 次数
A      4
B      2
C      2现在要增加一列为所有人总次数,姓名 次数  总次数
A      4     8
B      2     8
C      2     8请问怎么写代码查询效率高?

解决方案 »

  1.   

    select distinct 姓名,count(*) over(partition by 姓名) 次数,count(*) over() 总次数
    from t
      

  2.   


    你上面的逻辑是不对的应该加上group byselect 姓名, (case when 姓名='A' then count(*) 
    when 姓名='B' then count(*) 
    when 姓名='C' then count(*) 
    end) 次数 
    from 表T group by 姓名;加上总数的sql是select t.*,  t2.* from (select 姓名, (case when 姓名='A' then count(*) 
    when 姓名='B' then count(*) 
    when 姓名='C' then count(*) 
    end) 次数
    from 表T group by 姓名) t, (select count(rowid) 总次数 from 表T) t2;
      

  3.   

    谢谢hebo2005和inthirties的解答!
    但是如果加上时间,并且某个时间范围内有人是没有数据的,应该怎么统计?
    情况如下:有一张表(T),其中关键列如下: 姓名 时间
    A   2008-1-1
    B   2008-2-2
    A   2008-1-1
    B   2008-1-3
    A   2008-1-2
    C   2008-2-1
    C   2008-2-2
    A   2008-1-31然后再分类统计: select 姓名, 
    (case when 姓名=‘A’ then count(*) 
    when 姓名=‘B’ then count(*) 
    when 姓名=‘C’ then count(*) 
    end) 次数 
    from T 
    where 时间 between
                   to_date('2009-2-1', 'yyyy-mm-dd hh24:mi:ss') and
                   to_date('2009-2-2 23:59:59', 'yyyy-mm-dd hh24:mi:ss')
    order by 姓名结果如下:
    姓名 次数        
    B      1
    C      2 这个时候姓名A是不存在了,如果我要改成下面的格式,应该怎么写代码?
    姓名 次数
    A       0 
    B      1
    C      2 谢谢!
      

  4.   

    select a.姓名,nvl(b.次数,0) 次数,nvl(b.总次数,0) 总次数
    from (
    select disitnct 姓名
    from 
    t) a,(
    select distinct 姓名,count(*) over(partition by 姓名) 次数,count(*) over() 总次数 
    from t
    where 时间 between 
                  to_date('2009-2-1', 'yyyy-mm-dd hh24:mi:ss') and 
                  to_date('2009-2-2 23:59:59', 'yyyy-mm-dd hh24:mi:ss') 
    ) b
    where a.姓名=b.姓名(+)
      

  5.   

    明白了,万分感谢hebo2005,结贴。