个别SELECT语句输出正确,当JOINed时输出不正确

时间:2019-02-10 13:30:51

标签: sqlite

我尝试使用小写字母和大写字母来解决此问题,但都失败了。

我有来自FDIC的银行业务数据集。

当我分别运行每个SELECT语句时,我会收到正确的输出:

SELECT
AVG(PCR.lnlsdepr) as NetLoansAndLeasesToDeposits
FROM 
All_Reports_20160331_Performance_and_Condition_Ratios as 
PCR

输出:(77%)

76.6238024035116

分别运行的第二条SELECT语句也是正确的(例如,它将少于25万美元的银行帐户中的金额输出为5.2万亿美元:

SELECT
sum(CAST(LD.IDdepsam as int)) AS 
DepositAccountsWith$LessThan$250k
FROM 
'All_Reports_20160331_Deposits_Based_on_the_
$250,000_Reporting_Threshold' as LD

正确的产出:(5,216,146,035,000美元,5.2万亿美元)

5216146035

但是,当我将两个查询合并为一个查询时,第二个输入的输出是错误的。例如它输出少于25万美元的美国银行帐户中的总金额,即31万亿美元,而不是5.2万亿美元。

SELECT
AVG(PCR.lnlsdepr) as NetLoansAndLeasesToDeposits,
sum(CAST(LD.IDdepsam as int)) AS 
DepositAccountsWith$LessThan$250k
FROM 
'All_Reports_20160331_Deposits_Based_on_the_$250,000_ 
 Reporting_Threshold' as LD
JOIN 
All_Reports_20160331_Performance_and_Condition_Ratios 
as PCR

输出: enter image description here

我尝试将所有内容都转换为小写,但仍然收到错误的输出:

select 
avg(pcr.lnlsdepr) as 'NetLoansAndLeASesToDeposits',
sum(cast(ld.IDdepsam as int)) as 
'DepositAccountsWith$LessThan$250k'
from 
'All_Reports_20160331_Deposits_BASed_on_the_
$250,000_Reporting_Threshold' as ld
join 
'All_Reports_20160331_Performance_and_Condition_Ratios' 
as pcr 

输出(不正确): enter image description here

我尝试使用大写字母,但仍收到不正确的输出: enter image description here

2 个答案:

答案 0 :(得分:1)

问题是每个表中都有多行并且它们正在相乘。

SELECT x.NetLoansAndLeasesToDeposits, y."DepositAccountsWith$LessThan$250k"
FROM (SELECT AVG(PCR.lnlsdepr) as NetLoansAndLeasesToDeposits
      FROM 
All_Reports_20160331_Performance_and_Condition_Ratios as 
PCR
     ) x CROSS JOIN
     (SELECT sum(CAST(LD.IDdepsam as int)) AS 
"DepositAccountsWith$LessThan$250k"
      FROM 
"All_Reports_20160331_Deposits_Based_on_the_
$250,000_Reporting_Threshold" LD
     ) y;

答案 1 :(得分:1)

为什么要加入这两个数据集?
您需要的结果可以独立计算,因为它们不相关,并显示为1行:

SELECT 
  (SELECT AVG(lnlsdepr)
  FROM All_Reports_20160331_Performance_and_Condition_Ratios) 
  AS NetLoansAndLeasesToDeposits,
  (SELECT sum(CAST(IDdepsam as int))
  FROM 'All_Reports_20160331_Deposits_Based_on_the_$250,000_Reporting_Threshold') 
  AS DepositAccountsWith$LessThan$250k

这样,您不需要加入开销。