chinye2020 (9/19/2012)
...
DONE!
That's not opening and closing balance - it's simply the amounts of the first and last transactions in the date range.
SELECT
a.AccNo,
t.Total_Adjustment,
t.Total_Topup,
t.Total_Comm,
t.Total_Transfer,
t.Total_RecvTransfer,
t.Total_Maxis,
t.Total_Digi,
t.Total_Celcom,
Option3.Open_Balance + t.TransactionsForPeriod AS ClosingBalance
FROM Tbl_Account a
LEFT JOIN (
SELECT
d.Transaction_AccNo,
SUM(d.Amount) AS TransactionsForPeriod,
SUM( case when d.TransType_ID = 0 then d.Amount else 0 end ) as Total_Adjustment,
SUM( case when d.TransType_ID = 1 then d.Amount else 0 end ) as Total_Topup,
SUM( case when d.TransType_ID = 2 then d.Amount else 0 end ) as Total_Comm,
SUM( case when d.TransType_ID = 3 then d.Amount else 0 end ) as Total_Transfer,
SUM( case when d.TransType_ID = 4 then d.Amount else 0 end ) as Total_RecvTransfer,
SUM( case when d.TransType_ID = 2 AND d.Topup_Company = 'M' then d.Amount else 0 end ) as Total_Maxis,
SUM( case when d.TransType_ID = 2 AND d.Topup_Company = 'D' then d.Amount else 0 end ) as Total_Digi,
SUM( case when d.TransType_ID = 2 AND d.Topup_Company = 'C' then d.Amount else 0 end ) as Total_Celcom
FROM (
SELECT
ti.Transaction_AccNo,
ti.TransType_ID,
p.Topup_Company,
Amount = SUM(ti.Amount)
FROM Tbl_Transaction ti
LEFT JOIN Tbl_Topup p ON p.Topup_ID = t.Topup_ID
WHERE ti.Transaction_Date >= convert(Date,'2012-09-1', 105)
AND ti.Transaction_Date < convert(Date,'2012-10-01', 105)
GROUP BY ti.Transaction_AccNo, ti.TransType_ID, p.Topup_Company
) d
GROUP BY d.Transaction_AccNo
) t
ON t.Transaction_AccNo = a.AccNo
OUTER APPLY ( -- SUM of all the amounts prior to date range
SELECT
Open_Balance = SUM(ti.Amount)
FROM Tbl_Transaction ti
WHERE ti.Transaction_AccNo = a.AccNo -- outer ref
AND ti.Transaction_Date < convert(Date,'2012-09-1', 105)
) Option3
ORDER BY a.AccNo
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden