SQL query to compare product sales by month

后端 未结 6 1048
无人共我
无人共我 2021-02-10 07:52

I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:

Category | Revenue  |  Yearh  |  Month
B         


        
6条回答
  •  失恋的感觉
    2021-02-10 08:37

    About the markdown - Yeah that is frustrating. The editor did preview my HTML table, but after posting it was gone - So had to remove all HTML formatting from the post...

    @kcrumley I think we've reached similar conclusions. This query easily gets real ugly. I actually solved this before reading your answer, using a similar (but yet different approach). I have access to create stored procedures and functions on the reporting database. I created a Table Valued function accepting a product category and a financial year as the parameter. Based on that the function will populate a table containing 12 rows. The rows will be populated with data from the view if any sales available, if not the row will have 0 values.

    I then join the two tables returned by the functions. Since I know all tables will have twelve roves it's allot easier, and I can join on Product Category and Month:

    SELECT 
        SP1.Program,
        SP1.Year,
        SP1.Month,
        SP1.TotalRevenue AS ThisYearRevenue,
        SP2.TotalRevenue AS LastYearRevenue
    FROM GetFinancialYear(@Category, 'First Look',  2008) AS SP1 
         RIGHT JOIN GetFinancialYear(@Category, 'First Look',  2007) AS SP2 ON 
             SP1.Program = SP2.Program AND 
             SP1.Month = SP2.Month
    

    I think your approach is probably a little cleaner as the GetFinancialYear function is quite messy! But at least it works - which makes me happy for now ;)

提交回复
热议问题