大家好!现我有一表A,其中数据为:
    SAVETIME         MOORMT STATUS  
1 2009-7-9 13:28:37 1 DELIVRD
2 2009-7-9 13:28:35 0
3 2009-6-22 16:18:48 1 DELIVRD
4 2009-6-22 16:18:48 0
5 2009-6-22 11:18:52 1 FAIL
6 2009-6-22 11:18:52 0
7 2009-6-22 9:47:56 1 DELIVRD
8 2009-6-22 9:47:56 0
9 2009-6-22 9:44:05 1 DELIVRD
现,我想查出按日期to_char(savetime,'yyyy-mm-dd')格式统计,在每天中moormt为1的条数,moormt为0的条数,及moormt为1且status为'DELIVRD'的条数,结果模式如下:
日期       mo  mt  success
2009-7-9   1   1   1
2009-6-22  4   4   3
请问该SQL该怎样写?

解决方案 »

  1.   

    select to_char(savetime,'yyyy-mm-dd')日期,
      count(decode(moormt,1,1))mo,
      count(decode(moormt,0,1))mt,
      count(case when moormt=1 and status='DELIVRD' then 1 end)success
    from a
    group by to_char(savetime,'yyyy-mm-dd')
    order by 日期
      

  2.   

    select to_char(savetime,'yyyy-mm-dd'),
           sum(case when moormt=1 then 1 else 0 end) as sum_moormt1,
           sum(case when moormt=0 then 1 else 0 end) as sum_moormt0,
           sum(case when moormt=1 and status='DELIVRD' then 1 else 0 end) as m1sd
    from A
    group by to_char(savetime,'yyyy-mm-dd')
      

  3.   

    --顶楼上的,应该用sum,而不是count 
    select to_char(savetime,'yyyy-mm-dd')日期, 
      sum(case when moormt=1 then 1 else 0 end )mo, 
      sum(case when moormt=0 then 1 else 0 end )mt, 
      sum(case when moormt=1 and status='DELIVRD' then 1 end)success 
    from a 
    group by to_char(savetime,'yyyy-mm-dd') 
    order by 日期  
      

  4.   


    count主要统计个数,为0的也统计进去了sum主要统计总数,对为0的累加,总数还是不变
      

  5.   

    我的decode
    后面没有多余的else选项
    不是0,是空
    null不会加入count计算
      

  6.   


    如果moormt有2,3等情况会出错,将decode(moormt,1,1)改为decode(moormt,1,1,0)这种格式就更严谨了。
      

  7.   


    ...
    出什么错?
    如果moormt为2、3、4有什么关系,不符合条件直接Null掉,换成0就严谨?
    不是一样的吗
      

  8.   

    问个问题如果为空,count是否会统计出
      

  9.   

    如果count(a)a为空,则不会统计
    若count(1) a 为空,照样统计
      

  10.   

    谢谢。晕4,那我之前的统计都是count(*)不都把空过滤掉了
      

  11.   

    count(*)统计的是记录数,不会把空列过滤的.除非该记录所有列为空,可是这样的话这条记录还属于这个表么?赫赫