请问如何用最简单的sql语言实现这个功能?

thor1080 2003-08-15 10:52:32
我选出一批数据后,想用最后一个数据减去第一个数据得到的差值,这是我想要的最后结果。
比如我根据条件选出了5,4,63,54,2,15,4,2这批数据并继续选出2-5=3这个结果
现在我想用尽量少的sql语句同时完成这两个功能,应该怎么写呢?
select ... from table where
...全文
23 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
thor1080 2003-08-15
  • 打赏
  • 举报
回复
谢谢两位大虾细心解答
thor1080 2003-08-15
  • 打赏
  • 举报
回复
more_zou兄的解答中,id是不能显示出来的,因为我得把这段语句用在程序中,不能给别人看id值
beckhambobo 2003-08-15
  • 打赏
  • 举报
回复
呵呵,笔误
last(value1) over()-first(value1) over() value2

last_value(value1) over()-first_value(value1) over() value2
beckhambobo 2003-08-15
  • 打赏
  • 举报
回复
select value1,last(value1) over()-first(value1) over() value2,value3 from
(select value1,value3 from table1 where....
union
select value4,value5 from table2 where...)
beckhambobo 2003-08-15
  • 打赏
  • 举报
回复
select value1,last(value1) over()-first(value1) over() value2,value3 from
(select value1,value3 from table1 where....
union
select value4,value5 from table2 where...)
thor1080 2003-08-15
  • 打赏
  • 举报
回复
噢,差不多了,不过我只需要-3,也就只需要返回一条记录,我自己也去试试看
more_zou 2003-08-15
  • 打赏
  • 举报
回复
是不是这样
more@xgis.more>select id,last_value(id)over()-first_value(id)over() result from num_table;

ID RESULT
---------- ----------
5 -3
4 -3
63 -3
52 -3
2 -3
15 -3
4 -3
2 -3

已选择8行。
thor1080 2003-08-15
  • 打赏
  • 举报
回复
谢谢
还想更进一步的请教一下,可否不用union来实现?
因为我是要选出很多值,而那个差值只是其中之一,而且我已经用了union,也就是说其实我的情况是:
select value1,value2,value3 from table1 where....union select value4,value5 from table2 where...
而value2就是我想要的差值(2-5=3),也就是beckhambobo兄提供的那个结果
beckhambobo 2003-08-15
  • 打赏
  • 举报
回复
sorry,用union all比较合适
select col_num from table where ...
union all
selcct last_value(col_num) over()-first_value(col_num) over() from table where ... and rownum=1;
beckhambobo 2003-08-15
  • 打赏
  • 举报
回复
select col_num from table where ...
union
selcct last_value(col_num) over(order by rownum)-first_value(col_num) over(order by rownum) from table where ... and rownum=1;

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧