您好我有以下数据:
Item daytime sub_hours ch_size
-------------------------------------------------------
t23 18-Aug-17 03:30:00 0.5 56.8
t23 18-Aug-17 04:00:00 0.5
t24 18-Aug-17 02:30:00 0.5 40.8
t24 18-Aug-17 04:40:00 0.5
t24 18-Aug-17 02:30:00 0 45.4
t23 19-Aug-17 03:30:00 0.5 70.2
t23 19-Aug-17 04:00:00 0.5
t24 19-Aug-17 02:30:00 0.5 40.8
t24 19-Aug-17 04:40:00 0.5
t24 19-Aug-17 02:30:00 0.2
我想得到这个结果:
Item daytime sub_hours ch_size
-------------------------------------------------------
t23 18-Aug-17 03:30:00 0.5 56.8
t23 18-Aug-17 04:00:00 0.5 56.8
t24 18-Aug-17 02:30:00 0.5 40.8
t24 18-Aug-17 04:40:00 0.5 40.8
t24 18-Aug-17 02:30:00 0 45.4
t23 19-Aug-17 03:30:00 0.5 70.2
t23 19-Aug-17 04:00:00 0.5 70.2
t24 19-Aug-17 02:30:00 0.5 40.8
t24 19-Aug-17 04:40:00 0.5 40.8
t24 19-Aug-17 02:30:00 0.2
我需要更新ch_size列,将其设置为前一个值,其中
ch_size为null,sub_hours = 0.5:
这是我使用的代码:
update day_status a set ch_size =
( select prev_choke from
(
select LAG(ch_size) OVER (order by item, daytime) as prev_choke
from day_status
where trunc(daytime) between to_date('1 Aug 2017') and to_date('31 Aug 2017')
) b where a.item = b.item and a.daytime=b.daytime
)
我还没有测试过这段代码,你认为它是正确的并且达到我想要的结果吗?
感谢, 小号
答案 0 :(得分:0)
您可以使用LAG功能。它将为您提供上一行的值。
SELECT empno,
ename,
job,
sal,
LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_prev,
sal - LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_diff
FROM emp;
EMPNO ENAME JOB SAL SAL_PREV SAL_DIFF
---------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 800 0 800
7900 JAMES CLERK 950 800 150
7876 ADAMS CLERK 1100 950 150
7521 WARD SALESMAN 1250 1100 150
7654 MARTIN SALESMAN 1250 1250 0
7934 MILLER CLERK 1300 1250 50
7844 TURNER SALESMAN 1500 1300 200
7499 ALLEN SALESMAN 1600 1500 100
7782 CLARK MANAGER 2450 1600 850
7698 BLAKE MANAGER 2850 2450 400
7566 JONES MANAGER 2975 2850 125
7788 SCOTT ANALYST 3000 2975 25
7902 FORD ANALYST 3000 3000 0
7839 KING PRESIDENT 5000 3000 2000
答案 1 :(得分:0)
假设item
和daytime
是主键
UPDATE day_status a
SET a.ch_size =
(
SELECT LAG(ch_size) OVER (ORDER BY item, daytime) as prev_choke
FROM day_status b
WHERE a.item = b.item AND a.daytime=b.daytime
)
WHERE a.ch_size IS NULL AND a.sub_hours = 0.5