前几天同事问我一个问题,能不能用sql搞定这个问题:
我这里有一个张表table1中有time1,value1,有表table2有字段time2,value2。
现在要把table2中的value2更新到table1的value1中,要求time2距离time1最近。
一下子就想到之前学到的over partititon,但是只是学的时候操作了几个例子,一下子也没写上来。
后来找到一个教程http://blog.csdn.net/ayou2008/article/details/7179001
- select e.ename,
- e.job,
- e.sal,
- e.deptno,
- lead(e.sal, 1, 0) over(partition by e.deptno order by e.sal) lead_sal,
- lag(e.sal, 1, 0) over(partition by e.deptno order by e.sal) lag_sal,
- nvl(lead(e.sal) over(partition by e.deptno order by e.sal) - e.sal,
- 0) diff_lead_sal,
- nvl(e.sal - lag(e.sal) over(partition by e.deptno order by e.sal), 0) diff_lag_sal
- from scott.emp e;
稍微修改一下即可,diff_lead_sal, diff_lag_sal 和sal做差 两个差中找比较小的一个
请诸位试试能不能做到。
但是感觉效率很差,大家有没有好的方法啊?那哥们要离职了,根本不考虑太多,拿起我的方案就用...