Hi,@Jonathan Brotto
Welcome to Microsoft T-SQL Q&A Forum!
As you mentioned, you want to perform ‘yearly comparisons’, so if there is a column in the table that contains the value of date, maybe you can have a try on dynamic PIVOT.
I have a sample below, please check.
CREATE TABLE #TEST(ID INT,
AMOUNT INT,
Test_Date DATETIME
)
INSERT INTO #TEST VALUES
(01,89,'2019.10.01'),
(02,45,'2019.12.13'),
(01,23,'2020.11.01'),
(02,45,'2020.12.01'),
(01,78,'2021.09.02'),
(02,86,'2021.09.24')
DECLARE @sql_str VARCHAR(8000)
DECLARE @sql_col VARCHAR(8000)
--Get the possible column names from the row data
SELECT @sql_col = ISNULL(@sql_col + ',','') + QUOTENAME(YEAR(Test_Date))
FROM #TEST
GROUP BY YEAR(Test_Date)
--PRINT @sql_col
SET @sql_str = '
SELECT * FROM (
SELECT ID,YEAR(Test_Date)AS TestYear,AMOUNT FROM #TEST) S
PIVOT (MAX(AMOUNT) FOR TestYear IN ( '+ @sql_col +') ) AS P
ORDER BY P.ID'
--PRINT (@sql_str)
EXEC (@sql_str)
Output:
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. 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.