按1列中的特定旧值和新值更新列

时间:2015-12-01 19:54:17

标签: sql oracle plsql oracle11g oracle-sqldeveloper

enter image description here

这是一个日志表,所有卡都更改了这个表中保存的值现在我添加列来插入卡的旧值问题是我想在代码中执行的是一个程序扫描表而且旧的值在新专栏。什么是旧值,旧值是相同的值,卡不重复,然后它没有旧值,但如果它重复,所以有一个旧的值我上传的图像标识我想做的事情谢谢你的帮助:) / p>

1 个答案:

答案 0 :(得分:0)

这应该指向正确的方向以查看如何跟踪先前的值(我假设一个名为TS的时间戳字段来跟踪给定card_code的实例顺序。您需要调整以满足您的数据模型)。你只需要围绕它进行更新,为给定的card_Code和TS设置total_number_o。

with tab as ( 
          select 101012172583 card_code, '005' total_number, sysdate ts from dual
union all select 101012172583 card_code, '006' total_number, sysdate-1/12 ts  from dual
union all select 101012172583 card_code, '003' total_number, sysdate-2/12 ts  from dual
union all select 101012172583 card_code, '003' total_number, sysdate-3/12 ts  from dual
union all select 101012172583 card_code, '005' total_number, sysdate-4/12 ts  from dual
union all select 101012172583 card_code, '004' total_number, sysdate-5/12 ts  from dual
            )
select card_Code
     , total_number
     , lag(total_number) over ( partition by card_code order by ts) total_number_o
     , ts 
from tab order by card_Code, ts desc;     

CARD_CODE                              TOTAL_NUMBER   TOTAL_NUMBER_O   TS                     
101012172583                           "005"          "006"            01/12/2015 3:16:35 PM  
101012172583                           "006"          "003"            01/12/2015 1:16:35 PM  
101012172583                           "003"          "003"            01/12/2015 11:16:35 AM 
101012172583                           "003"          "005"            01/12/2015 9:16:35 AM  
101012172583                           "005"          "004"            01/12/2015 7:16:35 AM  
101012172583                           "004"                           01/12/2015 5:16:35 AM