我遇到问题的直接聚合选择语句。
当我第一次运行这个查询时,没有问题:
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
非常感谢任何输入或建议!