Hi @Amir ,
Welcome to the microsoft TSQL Q&A forum!
Sorry, your question is not clear enough for me, you mentioned Balance Today-Balance Last Year, but today’s balance has two data according to different AccountNumber: 45 and 345, which one should we choose?
Similarly, you mentioned calculate Volume Movements (e.g. Number of account Today-Number of accounts Last Year) by Segment. But some segments under the same date have different AccountNumbers, such as
The AccountNumber of 2021-08-18 contains 123 and 456. Which one should we choose?
The following is a method based on my guess, please check if it works for you:
;WITH cte
as(SELECT * FROM (SELECT SnapshotDate,AccountNumber,Segment,Balance
FROM #Data) t
PIVOT (MAX(Balance) FOR SnapshotDate
IN([2021-08-18],[2021-08-15],[2021-07-31],[2021-06-30],[2020-12-31])) p)
SELECT AccountNumber,Segment,[2021-08-18] BalanceToday,
[2021-08-18]-[2021-08-15] AS WTD_Value,
[2021-08-18]-[2021-07-31] AS MTD_Value,
[2021-08-18]-[2021-06-30] AS QTD_Value,
[2021-08-18]-[2020-12-31] AS YTD_Value
FROM cte
Output:
;WITH cte
as(SELECT SnapshotDate,Segment,SUM(AccountNumber) AccountNumber
FROM #Data
GROUP BY SnapshotDate,Segment)
,cte2 as(SELECT * FROM (SELECT SnapshotDate,AccountNumber,Segment
FROM cte) c
PIVOT (MAX(AccountNumber) FOR SnapshotDate
IN([2021-08-18],[2021-08-15],[2021-07-31],[2021-06-30],[2020-12-31])) p)
,cte3 as(SELECT * FROM (SELECT SnapshotDate,AccountNumber,Segment,Balance
FROM #Data) t
PIVOT (MAX(Balance) FOR SnapshotDate
IN([2021-08-18],[2021-08-15],[2021-07-31],[2021-06-30],[2020-12-31])) p)
SELECT c3.Segment,c3.[2021-08-18] BalanceToday,
c3.[2021-08-18]-c3.[2021-08-15] AS WTD_Value,
c3.[2021-08-18]-c3.[2021-07-31] AS MTD_Value,
c3.[2021-08-18]-c3.[2021-06-30] AS QTD_Value,
c3.[2021-08-18]-c3.[2020-12-31] AS YTD_Value,
c2.[2021-08-18]-c2.[2021-08-15] AS WTD_Volume,
c2.[2021-08-18]-c2.[2021-07-31] AS MTD_Volume,
c2.[2021-08-18]-c2.[2021-06-30] AS QTD_Volume,
c2.[2021-08-18]-c2.[2020-12-31] AS YTD_Volume
FROM cte2 c2
JOIN cte3 c3 ON c2.Segment=c3.Segment
Output:
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
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.