I have a query that uses a bunch of case statements to aggregate sales by Division and Employee Id with the month and year as the column headings. Currently, I am using Case statements for each unique month and year. My goal is to try to find a more dynamic method to achieve the same result without having to add additional case statements for every new value that ends up in the Mnth_Yr column.
I have tried to use PIVOT, but the results were that all outcome was that all the row values were converted to columns instead of just the Mnth_Yr column.
Here is a sample of the data.
This is the desired results I am looking to achieve.
Here is the code that I am using.
IF OBJECT_ID('tempdb.dbo.#table_data') IS NOT NULL
DROP TABLE #table_data
CREATE table #table_data
([Division] varchar(15), [Emp_Id] int, [Mnth_Yr] int, [Sales] money)
INSERT INTO #table_data
([Division], [Emp_Id], [Mnth_Yr], [Sales])
VALUES
('Northeast', 625, 202101, 310.58),
('Northeast', 627, 202101, 252.83),
('Southeast', 158, 202101, 5871.12),
('Southeast', 487, 202101, 1587.58),
('Northeast', 625, 202102, 521.87),
('Northeast', 627, 202102, 870.24),
('Southeast', 158, 202102, 7812.17),
('Northeast', 625, 202103, 564.57),
('Northeast', 627, 202103, 251.61),
('Southeast', 158, 202103, 15780.45),
('Southeast', 487, 202103, 1770.51)
;
----------------------------------------------------------------------
select Division
, Emp_Id
, SUM(Case When Mnth_Yr = 202101 Then Sales ELSE null END) as "202101"
, SUM(Case When Mnth_Yr = 202102 Then Sales ELSE null END) as "202102"
, SUM(Case When Mnth_Yr = 202103 Then Sales ELSE null END) as "202103"
from #table_data
Group by Division
, Emp_Id

