首页 > 解决方案 > Left Join 不返回丢失的信息 - SQL Oracle

问题描述

一个是现金,另一个是舞台,结构如下

现金

FileID     Cash   Date
1           50   03.04.2017
2           100  08.07.2015
3           70   14.09.2018

阶段

FileID      Stage           Date_of_stage
1           Finished       06.04.2016
1           In Process     08.07.2015
2           Complication   17.08.2018
2           In Process     14.03.2018

虽然我的表有更多的行。所以我加入了这两张桌子,因为我想使用这个选择按阶段对现金进行分组:

select fileID,  date, cash, max(date_of_stage) as max_date
from (select c.fileID, c.date, c.cash, s.stage, s.date_of_stage  
      from cash c
      inner join stage s
      on c.fileID=s.fileID
      and s.date_of_stage < c.date
      ) x
group by fileID, date, cash 

我只需要 max(date_of_stage) 因为它在逻辑上对我们的报告有意义,而且这不是问题的一部分。

问题是:当我比较现金表和上述选择的总现金时,我从上述选择中得到的总金额比现金表中的总和少一点(现金为700 万,上述选择为 690 万)。现在我正在尝试使用左连接来识别丢失的记录:

select *
from (select fileID, date, cash
  from cash) x

left join 

(select fileID,  date, cash, max(date_of_stage) as max_date
from (select c.fileID, c.date, c.cash, s.stage, s.date_of_stage  
      from cash c
      inner join stage s
      on c.fileID=s.fileID
      and s.date_of_stage < c.date
      ) 
group by fileID, date, cash ) y
on x.fileID=y.fileID
and x.date=y.date
and x.cash=y.cash
where y.fileID is null

但是这个左连接没有给出任何东西,所以我无法识别和检查丢失的记录。任何提示该怎么做?

标签: sqloracleleft-join

解决方案


它很奇怪。使用您提供的“检查”查询的数据可以正常工作并显示两行。这是dbfiddle 演示

无论如何,如果您只需要从第二个表中附加最大日期,请使用简单的子查询:

select fileID,  date_, cash, 
       (select max(date_of_stage) 
          from stage s
          where fileid = c.fileid and s.date_of_stage < c.date_) as max_date
  from cash c

演示


推荐阅读