我使用oracle查询数据,要求是统计各个年份的人数,和总人数表EMPdate                                    last_name1999年12月13日                 mi1998年1月10日                     hi1999年2月8日                      ji 1998年4月16日                        chi
结果total          1998年               1999年         4                                  2                          2我写的语句如下:
select count(date) "1998",count(date) "1999",count(*) total
from emp
where to_char(date,'yyyy') in ('1998,1999')
group by date
但是结果不对,请大家指正,谢谢

解决方案 »

  1.   

    select count(*) as total,
    sum(decode(EXTRACT(YEAR from date),1998,1,0)) as "1998",
    sum(decode(EXTRACT(YEAR from date),1999,1,0)) as "1999"
    from EMP
      

  2.   

    select sum(decode(to_char(date,'yyyy'),'1998',1,0)) "1998",sum(decode(to_char(date,'yyyy'),'1999',1,0)) "1999",count(*) total
    from emp
    where date <to_date('20000101','yyyymmdd')
      and date>=to_date('19980101','yyyymmdd')
    将where条件改了一下,否则不会用到索引
      

  3.   

    select sum(1) as total, sum(decode(substr(date,1,4),'1998',1,0)) as '1998年',sum(decode(substr(date,1,4),'1999',1,0)) as '1999年' from tbl
      

  4.   

    select count(*) total,sum(decode(substr("date",1,4),'1998',1,0)) "1998年",sum(decode(substr("date",1,4),'1999',1,0)) "1999年" from emp;
      

  5.   

    SQL> edi
    已写入 file afiedt.buf  1  create table tb1
      2  (dt date,
      3  last_name varchar(5)
      4  )
      5* tablespace myts
    SQL> /表已创建。SQL> insert into tb1 values(to_date('19991231','yyyymmdd'),'mi');已创建 1 行。SQL> insert into tb1 values(to_date('19980110','yyyymmdd'),'hi');已创建 1 行。SQL> insert into tb1 values(to_date('19990208','yyyymmdd'),'ji');已创建 1 行。SQL> insert into tb1 values(to_date('19980416','yyyymmdd'),'chi');已创建 1 行。SQL> select * from tb1;DT             LAST_
    -------------- -----
    31-12月-99     mi
    10-1月 -98     hi
    08-2月 -99     ji
    16-4月 -98     chi正式代码:
    SQL> edi
    已写入 file afiedt.buf  1  select count(*) as total1,sum(decode(substr(to_char(dt,'yyyymmdd'),1,4),'1998',1,0)) as "1998",
      2  sum(decode(substr(to_char(dt,'yyyymmdd'),1,4),'1999',1,0)) as "1999"
      3* from tb1
    SQL> /    TOTAL1       1998       1999
    ---------- ---------- ----------
             4          2          2