Hi @abiodunajai
I've made some changes to your script for your new needs. You can give it a try.
DECLARE @EndDate DATE = '2021-01-01' -- Cut off Date for Opening balances
DECLARE @BDate DATE = '2021-01-01' -- Transaction begin Date specify by the user
DECLARE @EDate DATE = '2023-03-16' -- Transaction End Date Specifiy by the user
DECLARE @ClientCode CHAR(10)
DECLARE @DigitalCode CHAR(3)
SET @ClientCode ='0000000065' -- Client Code Specify by the user
SET @DigitalCode='566'
DROP TABLE IF EXISTS #Statement
DROP TABLE IF EXISTS #temp
create table #temp(a int);
insert into #temp values(1);
;with PastBal As (
SELECT DebitNoteNo, TransDate, ClientCode, Particular, Amount As Amount
FROM InvoiceTable WHERE TransDate >=@EndDate AND TransDate < @BDate AND ClientCode=@ClientCode
UNION ALL
SELECT ReceiptCode, TransDate, ClientCode, Particular, -Amount As Amount
FROM ReceiptTable WHERE TransDate >=@EndDate AND TransDate < @BDate AND ClientCode=@ClientCode
),OpenBalance As(
SELECT ClientCode,Sum(Amount) As Amount FROM PastBal GROUP BY ClientCode
),Stm As(
select 'N/A' As DebitNoteNo,null as TransDate,'N/A' as ClientCode,'B/F' as Particular,
'0' as Amount from #temp where @EndDate = @BDate
union all
SELECT 'N/A' As DebitNoteNo, DATEADD(day,-1, @BDate) As TransDate, ClientCode,
'**BROUGHT FORWARD**' As Particular, Amount FROM OpenBalance
UNION ALL
SELECT DebitNoteNo, TransDate, ClientCode, Particular, Amount As Amount FROM InvoiceTable WHERE TransDate >=@BDate AND TransDate < @EDate AND ClientCode=@ClientCode
UNION ALL
SELECT ReceiptCode As DebitNoteNo, TransDate, ClientCode, Particular, Amount FROM ReceiptTable WHERE TransDate >=@BDate AND TransDate <= @EDate AND ClientCode=@ClientCode
)
SELECT IDENTITY(int, 1, 1) AS ROW_ID, ClientCode, DebitNoteNo, TransDate, Particular, Amount
INTO #Statement
FROM stm
ORDER BY TransDate, DebitNoteNo
;with CTE as(
SELECT ROW_ID, ClientCode, COALESCE(DebitNoteNo, '') As DebitNoteNo,
COALESCE(TransDate, GETDATE()) AS TransDate,
COALESCE(a.Particular, '**BALANCE**') AS Particular, COALESCE(Amount,0) As Amount
FROM #Statement a
GROUP BY GROUPING SETS((ROW_ID, DebitNoteNo, ClientCode, TransDate, Particular, Amount), ()))
select *,SUM(Amount) OVER(ORDER BY CASE WHEN ROW_ID IS NULL THEN 1 ELSE 0 END, ROW_ID) As ClientBalance
from CTE ORDER BY CASE WHEN ROW_ID IS NULL THEN 1 ELSE 0 END, ROW_ID;
Output:
Best regards,
Percy Tang
If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.