0

我遇到问题的直接聚合选择语句。

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

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

非常感谢任何输入或建议!

4

1 回答 1

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]
于 2013-04-11T18:14:54.643 回答