Reputation: 168
Greeting all.
I have a SQL Server 2008 Express database with a table called tbl_Sales
, similar as following:
Merchant | Sales | Month
Comp.1 100 201101
Comp.1 200 201102
Comp.2 130 201102
Comp.1 250 201103
Comp.2 130 201103
Comp.3 240 201103
.
.
.
Comp.3 340 201111
Comp.2 240 201112
Comp.3 140 201112
I want to generate the following data in MVC3 chart.
But the chart need all merchants' data every months else it will conflict.
So is there a way for SQL to do the result as following:
Merchant | Sales | Month
Comp.1 100 201101
Comp.2 0 201101
Comp.3 0 201101
Comp.1 200 201102
Comp.2 130 201102
Comp.3 0 201102
Comp.1 250 201103
Comp.2 130 201103
Comp.3 240 201103
.
.
.
Comp.3 340 201111
Comp.1 0 201112
Comp.2 240 201112
Comp.3 140 201112
We can have another table tbl_Merchant
list out all the Merchant we need as following:
Merchant
Comp.1
Comp.2
Comp.3
.
.
.
Comp.10
Any suggestion will be welcome.
Thank you very much.
Upvotes: 0
Views: 380
Reputation:
Yes - do a cartesian join of Merchants to Months to be reported (so that you get each month row for every merchant), then left join to your data table - like so:
select mth.[Month], mct.Merchant, coalesce(s.Sales,0) Sales
from (select distinct [Month] from tbl_Sales) mth
cross join Merchant mct
left join tbl_Sales s
on mth.[Month] = s.[Month] and mct.Merchant = s.Merchant
(If tbl_Sales is particularly large, it might be quicker to populate the mth
inline view with the necessary range of months from a recursive CTE-generated list of months, rather than selecting the necessary set of months from the Sales data.)
Upvotes: 2