sql - 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
但是这个左连接没有给出任何东西,所以我无法识别和检查丢失的记录。任何提示该怎么做?
解决方案
它很奇怪。使用您提供的“检查”查询的数据可以正常工作并显示两行。这是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
推荐阅读
- html - 缩小屏幕尺寸并管理边距
- ios - 用于 Ionic Angular 应用程序的 iOS 上的 SSL 固定
- android - XML 显示白屏
- image - 在 Xamarin 表单中显示来自另一个项目的图像
- php - 带有 Doctrine 的条件唯一约束
- asp.net - Gridview 多个复选框选择
- spring-boot - 在 docker compose 中使用不同的配置运行 spring boot docker image
- javascript - 从数组 React 中删除
- python - 为什么验证码图像 src 不会导致图像?
- reactjs - 在 localhost 上运行的前端和后端的 Cookie 传输问题