【问题标题】:Group By clause over a series of data SQL对一系列数据 SQL 的 Group By 子句
【发布时间】:2015-04-23 11:49:01
【问题描述】:

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

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

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 子句中。我考虑过使用公用表表达式,但不确定如何最好地利用它。任何见解将不胜感激。

感谢您的宝贵时间!

【问题讨论】:

  • 请标记使用的 dbms 产品! (使用了一些非 ANSI SQL...)

标签: sql report reporting grouping accounting


【解决方案1】:

您需要条件聚合。这会将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

【讨论】:

  • 非常感谢,这对我帮助很大!
猜你喜欢
  • 2012-04-24
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多