I have a view of the Monthly Status database. I need to create a report based on. The data in the view looks something like this:
Category | Revenue | Yearh | Month Bikes 10 000 2008 1 Bikes 12 000 2008 2 Bikes 12 000 2008 3 Bikes 15 000 2008 1 Bikes 11 000 2007 2 Bikes 11 500 2007 3 Bikes 15 400 2007 4
... And so on
The view has a product category, income, year and month. I want to create a report compared to 2007 and 2008, showing 0 for months without sales. Therefore, the report should look something like this:
Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400
The key point that should be noted is that month 1 has only sales in 2008 and therefore is 0 for 2007. In addition, the 4th month has no sales in 2008, therefore 0, while it has sales in 2007 and is still displayed.
In addition, the report is actually for the fiscal year - therefore, I would like the column “empty” to be 0, if there were no sales in the 5th month in 2007 or 2008.
The received request looks something like this:
SELECT SP1.Program, SP1.Year, SP1.Month, SP1.TotalRevenue, IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue FROM PVMonthlyStatusReport AS SP1 LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON SP1.Program = SP2.Program AND SP2.Year = SP1.Year - 1 AND SP1.Month = SP2.Month WHERE SP1.Program = 'Bikes' AND SP1.Category = @Category AND (SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND ((SP1.Year = @FinancialYear AND SP1.Month > 6) OR (SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6)) ORDER BY SP1.Year, SP1.Month
The problem with this query is that it will not return the fourth row in the examples above, since in 2008 we had no sales, but we really did it in 2007.
This is probably a common query / problem, but my SQL code is rusty after a long development. Any help is much appreciated!
Oh, by the way, I'm using SQL 2005 for this query, so if there are useful useful features that can help me tell me.