一个sql问题

wren4255 2014-04-23 12:57:38
我写一个sql文,其中有order by 按一定顺序排序
其中有a,b,c字段,我想取a=2的数据的上一条数据的b,并且上一条数据的c必须要=1
能实现么
...全文
154 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wren4255 2014-04-23
  • 打赏
  • 举报
回复
谢谢你们 太有参考价值了
gangma2 2014-04-23
  • 打赏
  • 举报
回复
可以使用lag函数:
lag(col,1,null) over(partition by col order by col)
lag函数是先分组再排序,并把当前行的上一个值放到该行中,lag(col,1,null)1表示增量字段,可以根据要求自定义,null是上一行不存在时用null代替,也可以自定义。
对于你的要求就不要分组了:
测试数据截图:

select b
from (select a, lag(b) over(order by a) b, lag(c) over(order by a) c
from my_test) t
where t.a = 2
and t.c = 1;

测试结果:
CT_LXL 2014-04-23
  • 打赏
  • 举报
回复
引用 楼主 wren4255 的回复:
我写一个sql文,其中有order by 按一定顺序排序 其中有a,b,c字段,我想取a=2的数据的上一条数据的b,并且上一条数据的c必须要=1 能实现么
with t as
 (select 1 a, 2 b, 3 c
    from dual
  union all
  select 2 a, 3 b, 1 c
    from dual
  union all
  select 2 a, 4 b, 3 c
    from dual
  union all
  select 2 a, 5 b, 1 c
    from dual
  union all
  select 4 a, 6 b, 1 c
    from dual)
select p_b
  from (select t.*, lag(b) over(order by a) p_b, lag(c) over(order by a) p_c
          from t) t1
 where t1.a = 2
   and p_c = 1;
流浪川 2014-04-23
  • 打赏
  • 举报
回复
select * from ( select * from tab where a<2 and c=1 order by a) where rownum=1 没太明白你的意思

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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