在Select语句中加入另一个表会产生不正确的高聚合总计

时间:2013-04-11 17:59:48

标签: sql-server join aggregate-functions multiple-tables

直接聚合选择语句我遇到了麻烦。

当我第一次运行此查询时,没有问题:

SELECT distinct 

t2.primary_insurance [Primary Insurance]
,COUNT(t2.account_number) [Volume]  
,SUM(t2.los) [Total LOS] 
,AVG(t2.los) [Avg LOS]  
,AVG(t1.drg_cost_weight) [Avg CMI] 
,sum(t2.total_charges) [Total Charges]
,sum(-t2.insurance_receipts) [Total Receipts]   

FROM 
[table1] t1
LEFT OUTER join
[table2] t2
on t1.account_number = t2.account_number

GROUP BY
t2.primary_insurance

order by 
[Primary Insurance]

但是一旦我添加Table3来聚合它的数据,它就会返回一个不同的[Volume]总数,这会使所有其他总数不正确。

SELECT distinct 

t2.primary_insurance [Primary Insurance]
,COUNT(t2.account_number) [Volume]  
,SUM(t2.los) [Total LOS] 
,AVG(t2.los) [Avg LOS]  
,AVG(t1.drg_cost_weight) [Avg CMI] 
,sum(t2.total_charges) [Total Charges]
,sum(-t2.insurance_receipts) [Total Receipts]
,sum(t3.[direct_cost]) [Direct Cost]
,sum(t3.[indirect_cost])[Indirect Cost]
,sum((t3.[direct_cost] + t3.[indirect_cost])) [Total Cost]
,sum((-t2.insurance_receipts - t3.[direct_cost])) [Contribution Margin] 
,sum((-t2.insurance_receipts - (t3.[direct_cost] + CR.[indirect_cost]))) [Profit]

from
[table1] t1
LEFT OUTER join
[table2] t2
on t1.account_number = t2.account_number
JOIN
[table3] t3
on t2.[account_number]  = t3.[account_number]

GROUP BY
t2.primary_insurance

order by 
[Primary Insurance]

我尝试过加入不同的方式,但不断获得相同的膨胀音量总数,而且无法从原始查询中获得音量总计(正确的音量总计)。要清楚,问题是第二个查询给出的总量高于第一个查询的总量。总量越高,其他所有内容的总数就越高。

我也尝试过使用子查询来获取table3数据,但也无法做到这一点。

除了添加table3并对该表中的各种数据求和之外,这两个查询是相同的。查询不会出错,只会给出不正确的总数。

使用SQL Server 2008

非常感谢任何意见或建议!

1 个答案:

答案 0 :(得分:0)

然后很清楚你在table3上复制了值,这意味着account_number不是该表上的主键(也不是唯一的)。您可以使用密钥(或该表上唯一的列集合)加入,也可以事先在该表上进行聚合:

SELECT  t2.primary_insurance [Primary Insurance]
        ,COUNT(t2.account_number) [Volume]  
        ,SUM(t2.los) [Total LOS] 
        ,AVG(t2.los) [Avg LOS]  
        ,AVG(t1.drg_cost_weight) [Avg CMI] 
        ,SUM(t2.total_charges) [Total Charges]
        ,SUM(-t2.insurance_receipts) [Total Receipts]
        ,SUM(t3.[direct_cost]) [Direct Cost]
        ,SUM(t3.[indirect_cost])[Indirect Cost]
        ,SUM((t3.[direct_cost] + t3.[indirect_cost])) [Total Cost]
        ,SUM((-t2.insurance_receipts - t3.[direct_cost])) [Contribution Margin] 
        ,SUM((-t2.insurance_receipts - (t3.[direct_cost] + CR.[indirect_cost]))) [Profit]
FROM [table1] t1 
LEFT JOIN [table2] t2
    ON t1.account_number = t2.account_number
LEFT JOIN ( SELECT  [account_number], 
                    SUM([direct_cost]) [direct_cost],
                    SUM([indirect_cost]) [indirect_cost]
            FROM [table3]
            GROUP BY [account_number]) t3
    ON t2.[account_number]  = t3.[account_number]
GROUP BY t2.primary_insurance
ORDER BY [Primary Insurance]