有一个表tmpdate                    name      used
2012/10/17 8:00:00      db1        20
2012/10/17 8:30:00      db1        23
2012/10/17 9:00:00      db1        32
2012/10/18 8:00:00      db1        15
2012/10/18 8:30:00      db1        18
2012/10/18 9:00:00      db1        21
2012/10/18 9:30:00      db1        25
求环比增长量,本次采集的时间点与上次采集的时间点相比used的增长量,请教sql语句求同比增长量,今天采集数据的时间点与昨天采集的相同的时间点相比used的增长量,请教sql语句,
对这一个表操作。。

解决方案 »

  1.   


    with t1 as
    (
         select '2012/10/17 8:00:00' c1,'db1' name,20 used from dual
         union all
         select '2012/10/17 8:30:00' c1,'db1' name,23 used from dual
         union all
         select '2012/10/17 9:00:00' c1,'db1' name,32 used from dual
         union all
         select '2012/10/18 8:00:00' c1,'db1' name,15 used from dual
         union all
         select '2012/10/18 8:30:00' c1,'db1' name,18 used from dual
         union all
         select '2012/10/18 9:00:00' c1,'db1' name,21 used from dual
         union all
         select '2012/10/18 10:00:00' c1,'db1' name,14 used from dual
         union all
         select '2012/10/19 8:00:00' c1,'db1' name,23 used from dual
         union all
         select '2012/10/19 10:00:00' c1,'db1' name,17 used from dual
    )select c1,name,used,
           round(used-lag(used) over(partition by name order by rownum),2) z1,
           round(used-lag(used) over(partition by to_char(to_date(c1,'yyyy/mm/dd hh24:mi:ss'),'hh24:mi:ss') order by c1),2) z2
    from t1
    order by to_date(c1,'yyyy/mm/dd hh24:mi:ss')
                c1         name  used   z1   z2
    ---------------------------------------------------------------
    1 2012/10/17 8:00:00 db1 20
    2 2012/10/17 8:30:00 db1 23 3
    3 2012/10/17 9:00:00 db1 32 9
    4 2012/10/18 8:00:00 db1 15 -17 -5
    5 2012/10/18 8:30:00 db1 18 3 -5
    6 2012/10/18 9:00:00 db1 21 3 -11
    7 2012/10/18 10:00:00 db1 14 -7
    8 2012/10/19 8:00:00 db1 23 9 8
    9 2012/10/19 10:00:00 db1 17 -6 3
      

  2.   

    round可以去掉 如果是求增加的比例可以使用
      

  3.   

    over  语句真强啊,得好好学习一下。
      

  4.   

    谢谢1楼的,
    但是执行的时候会报“文字与格式字符串不匹配”的错误
    我把partition by to_char(to_date(c1,'yyyy/mm/dd hh24:mi:ss'),'hh24:mi:ss') order by c1
    改为partition by to_char(c1,'hh24:mi:ss') order by c1order by to_date(c1,'yyyy/mm/dd hh24:mi:ss')
    也改为order by to_char(c1,'yyyy/mm/dd hh24:mi:ss')执行正确。
      

  5.   

    给分1楼吧,over用得很娴熟。