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

同一张表如何实现以下减法------江湖救急
NO ID Bed Date

1 11111 A-1 2011-1-4 11:04
2 11111 A-2 2011-2-4 11:04
3 11111 A-3 2011-3-4 11:04
4 11111 A-4 2011-4-4 11:04
5 11112 A-4 2011-6-4 11:04
6 11112 A-5 2011-7-4 11:04
7 11112 A-6 2011-8-4 11:04


大神,如上表内容,如何实现以 ID 相同的 以 Bed列分组  Date列 做减法,

第2行-第1行
第3行-第2行
第4行-第3行 
第6行-第5行
第7行-第6行
······

得到 
11111   A-1   31
11111   A-2   28
11111   A-3   31
11112   A-4   30
11112   A-5   31

  
分组

------解决方案--------------------
select b.id,b.bed,a.sj-b.sj from test_table a,test_table b
where a.no=b.no+1 and a.id=b.id
------解决方案--------------------
Connected to Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 
Connected as RCOTRPR1

SQL> select * from idcsdn;

        NO ID         BED        DAT
---------- ---------- ---------- -----------
         1 11111      A-1        1/4/2011 11
         2 11111      A-2        2/4/2011 11
         3 11111      A-3        3/4/2011 11
         4 11111      A-4        4/4/2011 11
         5 11112      A-4        6/4/2011 11
         6 11112      A-5        7/4/2011 11
         7 11112      A-6        8/4/2011 11

7 rows selected

SQL> 
SQL> SELECT no, id, bed, next_dat - dat
  2    FROM (SELECT no, id, bed, dat, lead(dat, 1) over(PARTITION BY id ORDER BY bed) AS next_dat FROM idcsdn)
  3   WHERE next_dat IS NOT NULL;

        NO ID         BED        NEXT_DAT-DAT
---------- ---------- ----------&nb