同一张表如何实现以下减法------江湖救急
NOIDBedDate
111111A-12011-1-4 11:04
211111A-22011-2-4 11:04
311111A-32011-3-4 11:04
411111A-42011-4-4 11:04
511112A-42011-6-4 11:04
611112A-52011-7-4 11:04
711112A-62011-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
---------- ---------- ---------- ------------
1 11111 A-1 31
2 11111 A-2 28
3 11111 A-3 31
5 11112 A-4 30
6 11112 A-5 31
SQL>
------解决方案--------------------
来晚了,2楼正解
------解决方案--------------------
这是分析函数中的偏移量函数的用法,就是2楼所说的