2015-04-23 13 views
0

我正在编写报告,并且在正确返回一系列数据(数据仓库可能是理想的,但现在不是一个选项)时遇到了一些麻烦。实际上,我需要加入并报告2个表格...对一系列数据的GROUP By子句SQL

交易和收据。交易包含收费金额和收据包含已付金额。我的报告需要显示:

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

--------------------------------------------------------------------- 
Tom  | Clark | Microsoft | Washington | $300 | $80 | $100 | $120 

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,但不知道如何最好地利用它。任何洞察力将是最赞赏。

谢谢你的时间!

+1

请标记DBMS产品! (一些非ANSI SQL使用...) – jarlh

回答

1

你想要条件聚合。这使casesum():使用

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 
+0

非常感谢,这对我帮助很大! –