Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在sql中读取以前的值_Sql_Oracle - Fatal编程技术网

如何在sql中读取以前的值

如何在sql中读取以前的值,sql,oracle,Sql,Oracle,我有一个存储ID、参考ID和金额的表。问题是,对于设置了引用ID的行,缺少数量。我需要读取reference_id=id的行,读取数量并设置值(如表2所示) 我希望能够展示: 表2 有人知道找到这个缺失值的最佳方法是什么吗? 顺致敬意, MEJ我想您需要一个自加入: select t1.id, t1.referenceid, coalesce(t2.amount, t1.amount) as amount from table1 t1 left outer join table1 t2

我有一个存储ID、参考ID和金额的表。问题是,对于设置了引用ID的行,缺少数量。我需要读取reference_id=id的行,读取数量并设置值(如表2所示)

我希望能够展示: 表2

有人知道找到这个缺失值的最佳方法是什么吗? 顺致敬意,
MEJ

我想您需要一个自加入:

select t1.id, t1.referenceid, coalesce(t2.amount, t1.amount) as amount
from table1 t1 left outer join
     table1 t2
     on t1.id = t2.referenceid;

我想你想要一个自我加入:

select t1.id, t1.referenceid, coalesce(t2.amount, t1.amount) as amount
from table1 t1 left outer join
     table1 t2
     on t1.id = t2.referenceid;

我认为您需要一个分层查询:

select id, ref_id, connect_by_root amount
from <your table>
connect by prior id = ref_id
start with ref_id is null;

.

我认为您需要分层查询:

select id, ref_id, connect_by_root amount
from <your table>
connect by prior id = ref_id
start with ref_id is null;

.

事实上,我以前也尝试过自连接。它没有给我想要的结果。。。使用自连接得到的结果与中的结果相同(我的示例中的表1)。我不知道我是否做错了什么。@user1495959。现在试试答案中的版本。事实上,我以前也尝试过自连接。它没有给我想要的结果。。。使用自连接得到的结果与中的结果相同(我的示例中的表1)。我不知道我是否做错了什么。@user1495959。现在尝试答案中的版本。
select id, ref_id, connect_by_root amount as amount
from <your table>
connect by prior id = ref_id and amount is null
start with ref_id is null or amount is not null
order by id;