-2

我的查询:

  select 
  SUM(payments.paid_amt) as paid_amt, 
  SUM(payments.copay_amt) as copay_amt,
  SUM(payments.CO_INSURANCE_AMT) as co_ins_amt,
  payor_group.PAYOR_GROUP as payor_group,
  DATEPART(MM,accession.XIFIN_LOAD_DATE) as load_month,
  DATEPART(yyyy,accession.XIFIN_LOAD_DATE) as load_year,
  accession.ACCESSION_ID


  from 
  [F_PAYOR_PAYMENTS_monthly] payments

  join D_PAYOR payor
  on payor.PAYOR_ID=payments.PAYMENT_PAYOR_ID

  join D_PAYOR_GROUP payor_group
  on payor.PAYOR_GROUP_KEY=payor_group.PAYOR_GROUP_KEY

  join F_ACCESSION_daily accession
  on accession.ACCESSION_ID=payments.ACCESSION_ID

  where accession.XIFIN_LOAD_DATE between '20120501' and '20120531'

  group by  payor_group.PAYOR_GROUP, DATEPART(MM,accession.XIFIN_LOAD_DATE),
  DATEPART(yyyy,accession.XIFIN_LOAD_DATE),accession.ACCESSION_ID

出于某种原因,它们多次SUMs计数相同。accession.ACCESSION_ID

当我进行所有这些连接时,我担心我可能SUMming多次使用相同的值。

我怎样才能确保我accession.ACCESSION_ID 只计算一次?

非常感谢您的帮助和指导。

4

2 回答 2

4

ACCESSION_ID您的付款表上可能有多行具有不同付款人组的相同行。由于您还按 payor_group 进行分组,因此您最终会得到多个登录 ID。

但是,我们需要查看一些示例数据才能确定。

于 2012-06-18T19:38:25.147 回答
3

问题是数据重复。

为了找出JOIN导致问题的原因,我会依次评论每一个并检查结果。创建额外数据的原因通常很明显。

如果没有看到数据,这很棘手,但是如果,例如,accession 表中有一个 GeographyKey,而 Payments 表没有,并且如果一个 ACCESSION_ID 出现在两个 GeographyKeys 上,那么在将这些表连接在一起时,您将获得两行数据在 ACCESSION_ID 上。

一种解决方案可能是在您的 OP 中点击查询之前对 #temp 表进行一些初始分组,另一种选择是 CTE,如下所示。

;with accession (XIFIN_LOAD_DATE, ACCESSION_ID)
    as 
    (
    select 
        XIFIN_LOAD_DATE
        ,ACCESSION_ID
    from F_ACCESSION_daily
    group by
         XIFIN_LOAD_DATE
         ,ACCESSION_ID
    )
    , payments (PAYMENT_PAYOR_ID, ACCESSION_ID, paid_amt, copay_amt, CO_INSURANCE_AMT)
    as 
    (
    select 
        PAYMENT_PAYOR_ID
         ,ACCESSION_ID
        ,sum(paid_amt) paid_amt
        ,sum(copay_amt) copay_amt
        ,sum(CO_INSURANCE_AMT) CO_INSURANCE_AMT
    from F_PAYOR_PAYMENTS_monthly
    group by
         PAYMENT_PAYOR_ID
         ,ACCESSION_ID
    )
select 
  SUM(payments.paid_amt) as paid_amt, 
  SUM(payments.copay_amt) as copay_amt,
  SUM(payments.CO_INSURANCE_AMT) as co_ins_amt,
  payor_group.PAYOR_GROUP as payor_group,
  DATEPART(MM,accession.XIFIN_LOAD_DATE) as load_month,
  DATEPART(yyyy,accession.XIFIN_LOAD_DATE) as load_year,
  accession.ACCESSION_ID

from 
  payments

  join D_PAYOR payor
  on payor.PAYOR_ID=payments.PAYMENT_PAYOR_ID

  join D_PAYOR_GROUP payor_group
  on payor.PAYOR_GROUP_KEY=payor_group.PAYOR_GROUP_KEY

  join accession
  on accession.ACCESSION_ID=payments.ACCESSION_ID

where accession.XIFIN_LOAD_DATE between '20120501' and '20120531'

group by  
  payor_group.PAYOR_GROUP
  , DATEPART(MM,accession.XIFIN_LOAD_DATE),
  DATEPART(yyyy,accession.XIFIN_LOAD_DATE),accession.ACCESSION_ID
于 2012-06-18T19:54:15.910 回答