对一系列数据的 Group By 子句 SQL

Group By clause over a series of data SQL

我正在编写报告,但在将一系列数据正确 return 时遇到了一些问题(数据仓库可能是理想的,但现在不是一个选项)。实际上,我有 2 个表需要加入并报告...

交易和收据。交易包含账单金额,收据包含支付金额。我的报告需要显示:

LastName | FirstName | Company | Location | Total | 30 | 60 | 90

---------------------------------------------------------------------
Tom      |  Clark | Microsoft | Washington | 0 |  | 0 | 0  

其中 30、60、90 是显示 30 天前、60 天前等欠款额的桶。这就是我正在努力的地方。我可以毫无问题地获得其他值。这是我到目前为止所拥有的:

select 
    st.Client_Name_Last,
    st.Client_Name_First,
    st.Location_Company,
    st.Location_Address_City,
    sum((st.Billing_AmountPerUnitAllowed * st.Billing_NumberOfUnits) - coalesce(r.PaymentAmount, 0)) as Total,
    (select sum((st.Billing_AmountPerUnitAllowed * st.Billing_NumberOfUnits) - coalesce(r.PaymentAmount, 0)) 
        where DateDiff(day, st.service_date,  @effectiveDate) > 0 and DateDiff(day, st.service_date,  @effectiveDate) < 30) as '30',
    (select sum((st.Billing_AmountPerUnitAllowed * st.Billing_NumberOfUnits) - coalesce(r.PaymentAmount, 0))
        where DateDiff(day, st.service_date,  @effectiveDate) >= 30 and DateDiff(day, st.service_date,  @effectiveDate) < 60) as '60'

 from 
    ServiceTransactions st
    join Claims c on st.Claim_Id = c.Id
    left outer join Receipts r on c.Id = r.ClaimId

group by 
    st.Client_Name_Last,    
    st.Client_Name_First,   
    st.Location_Company,
    st.Location_Address_City

这当然不行,因为 st.Service_Date 在顶层 select 语句中,这会导致错误,因为它不在聚合或 group by 子句中。我考虑过使用 Common Table Expression,但不确定如何最好地利用它。任何见解将不胜感激。

感谢您的宝贵时间!

您需要条件聚合。这将 case 放在 sum():

sum(case when DateDiff(day, st.service_date,  @effectiveDate) > 0 and DateDiff(day, st.service_date,  @effectiveDate) < 30)
         then (st.Billing_AmountPerUnitAllowed * st.Billing_NumberOfUnits) - 
              coalesce(r.PaymentAmount, 0)
          else 0
     end) as days_30,
sum(case when DateDiff(day, st.service_date,  @effectiveDate) >= 30 and DateDiff(day, st.service_date,  @effectiveDate) < 60)
         then (st.Billing_AmountPerUnitAllowed * st.Billing_NumberOfUnits) - 
              coalesce(r.PaymentAmount, 0)
          else 0
     end) as days_60