现有数据库结构如下:开始时间     结束时间     价格
2010-1-1     2010-1-10      1
2010-1-11    2010-1-20      2
2010-1-21    2010-1-30      3
先要求用sql查出某个时间段的价格之和
比如输入参数 开始时间:2010-1-5   结束时间:2010-1-25
结果应该是 5号到10号的价钱之和(6) +  11-20号的价钱之和(10)  + 21到25号的价钱之和(5)
而不是简单的三条记录的sum

解决方案 »

  1.   

    create table test
    (
    s_dt date,
    e_dt date,
    price number
    );insert into test values(to_date('20100101','yyyymmdd'),to_date('20100110','yyyymmdd'),1);
    insert into test values(to_date('20100111','yyyymmdd'),to_date('20100120','yyyymmdd'),2);
    insert into test values(to_date('20100121','yyyymmdd'),to_date('20100130','yyyymmdd'),3);
    select sum(case when to_date('20100105','yyyymmdd') between s_dt and e_dt then
           price*(e_dt - to_date('20100105','yyyymmdd')+1)
           when to_date('20100125','yyyymmdd') between s_dt and e_dt then
            price*( to_date('20100125','yyyymmdd') - s_dt +1)
           when to_date('20100105','yyyymmdd') < s_dt and to_date('20100125','yyyymmdd')>e_dt then
             price*(e_dt-s_dt+1)
             end)
             from test;
    -----------------------------------------------
    41
      

  2.   


    --参考
    select p1,p2,p3
    from (
         select (select price
                 from tb
                 where dt between to_date('20110105','yyyymmdd')
                              and to_date('20110110','yyyymmdd')) p1,
                (select price
                 from tb
                 where dt between to_date('20110111','yyyymmdd')
                              and to_date('20110120','yyyymmdd')) p2,
                (select price
                 from tb
                 where dt between to_date('20110121','yyyymmdd')
                              and to_date('20110125','yyyymmdd')) p3
         from dual)
    /
    select case when dt between to_date('20110105','yyyymmdd')and to_date('20110110','yyyymmdd')
                then price end p1,
           case when dt between to_date('20110111','yyyymmdd')and to_date('20110120','yyyymmdd')
                then price end p2,
           case when dt between to_date('20110121','yyyymmdd')and to_date('20110125','yyyymmdd')
                then price end p3
    from tb
    /