我正在編寫報告,並且在正確返回一系列數據(數據倉庫可能是理想的,但現在不是一個選項)時遇到了一些麻煩。實際上,我需要加入並報告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,但不知道如何最好地利用它。任何洞察力將是最讚賞。
謝謝你的時間!
請標記DBMS產品! (一些非ANSI SQL使用...) – jarlh