I’m working with a database view that contains monthly sales data and I need help creating a comparison report. Here’s what my data structure looks like:
Product_Type | Sales_Amount | Year_Val | Month_Val
Laptops 8500 2019 1
Laptops 9200 2019 2
Laptops 9800 2019 3
Laptops 7300 2018 1
Laptops 8100 2018 2
Laptops 8900 2018 3
Laptops 9650 2018 4
I want to build a report that compares sales between 2018 and 2019. The tricky part is that I need to show zero values for months where there were no sales in one year but sales in the other. My desired output should be:
Product_Type | Month_Val | Current_Year_Sales | Previous_Year_Sales
Laptops 1 8500 7300
Laptops 2 9200 8100
Laptops 3 9800 8900
Laptops 4 0 9650
I tried using a LEFT JOIN but it only shows records where the current year has data. How can I modify my query to include months that only exist in the previous year? I’m using SQL Server 2005 and would appreciate any suggestions for the best approach to solve this problem.