日期:2014-05-17  浏览次数:20663 次

特大难题,问题特别,详细请看内容。
表结构:
    出生日期     性别
    2006-07-01   女
    2006-07-04   男
    2006-07-06   男
    2005-07-01   男
    2005-07-01   女
    2007-07-01   男
    2007-07-01   女
    2007-07-01   女
    -------
得到下面的结构:
    年份     总男     总女     出生男     出生女
    2005       1           1             1             1
    2006       3           2             2             1
    2007       4           4             1             2

注释:
2006年的总男=2006年出生男+2005年的总男  


------解决方案--------------------
关注下cube等一类函数的使用
1. 自动汇总函数rollup,cube,
2. rank 函数, rank,dense_rank,row_number
3. lag,lead函数
4. sum,avg,的移动增加,移动平均数
5. ratio_to_report报表处理函数
6. first,last取基数的分析函数

------解决方案--------------------
SQL> select * from t;

BDAY S
---------- --
2004-02-04 女
2004-07-03 女
2006-03-05 女
2007-05-06 女
2007-08-03 男
2007-01-03 男
2007-10-25 男
2004-01-19 男

已选择8行。

SQL> select a.y,sum(nvl(b.s1,0)) over(order by a.y) t1,sum(nvl(b.s2,0)) over(order by a.y) t2, nvl(b.s1,0) s1,nvl(b.s2,0) s2 from (select to_char(2000+rownum) y from t connect by rownum <9) a, (select to_char(bday, 'yyyy ') y,sum(decode(s, '男 ',1,0)) s1 ,sum(decode(s, '男 ',0,1)) s2 from t group by to_char(bday, 'yyyy ')) b where a.y=b.y(+);

Y T1 T2 S1 S2
----- ---- ---- ---- ----
2001 0 0 0 0
2002 0 0 0 0
2003 0 0 0 0
2004 1 2 1 2
2005 1 2 0 0
2006 1 3 0 1
2007 4 4 3 1
2008 4 4 0 0

已选择8行。

------解决方案--------------------
select a.year as 年份,
(select count(*) from 表 where 出生日期 <=a.year|| '-12-31 ' and 性别= '男 ' ) as 总男,
(select count(*) from 表 where 出生日期 <=a.year|| '-12-31 ' and 性别= '女 ' ) as 总女,
(select count(*) from 表 where 出生日期 <=a.year|| '-12-31 ' and 出生日期> =a.year|| '-01--1 ' and 性别= '男 ' ) as 出生男,
(select count(*) from 表 where 出生日期 <=a.year|| '-12-31 ' and 出生日期> =a.year|| '-01--1 ' and 性别= '女 ' ) as 出生女

from (select distinct strsub(to_char(出生日期, 'YYYY-MM-DD '),1,4) year from 表 ) a