create table #Month ( [month] varchar(32))insert into #month ([month])select '1' [Month]union allselect '2' [Month]union allselect '3' [Month]union allselect '4' [Month]union allselect '5' [Month]-- drop table #reportcreate table #report (id int identity(1,1) not null, salesperson int)select 'alter table #report add [' + [month] + '] decimal(19,2) default 0' from #month/*alter table #report add [1] decimal(19,2) default 0alter table #report add [2] decimal(19,2) default 0alter table #report add [3] decimal(19,2) default 0alter table #report add [4] decimal(19,2) default 0alter table #report add [5] decimal(19,2) default 0*/-- drop table #invoicescreate table #invoices (invoiceid int, invoicedate datetime, invoicetotal decimal(19,2), salesperson int, clientid int) insert into #invoices (invoiceid, invoicedate, invoicetotal, salesperson, clientid)select 1, cast('2008-1-15' as datetime), 200, 1, 1union allselect 1, cast('2008-2-15' as datetime), 100, 1, 1union allselect 1, cast('2008-3-15' as datetime), 150, 1, 1-- all salespersons you wantinsert into #report (salesperson)select distinct salespersonfrom #invoiceswhere clientid = 1select 'update r set [' + cast(datepart(month, invoicedate) as varchar(32)) + '] = ''' + cast(sum(invoicetotal) as varchar(32)) + ''' from #report r where salesperson = ' + cast(i.salesperson as varchar(32))from #invoices iwhere i.salesperson in (select salesperson from #invoices)group by i.salesperson, datepart(month, i.invoicedate)/*update r set [1] = '200.00' from #report r where salesperson = 1update r set [2] = '100.00' from #report r where salesperson = 1update r set [3] = '150.00' from #report r where salesperson = 1*/select * from #report
truncate table #invoicesinsert into #invoices (invoiceid, invoicedate, invoicetotal, salesperson, clientid)select 1, cast('2008-1-15' as datetime), 200, 1, 1union allselect 1, cast('2008-2-15' as datetime), 100, 1, 1union allselect 1, cast('2008-3-15' as datetime), 150, 1, 1union allselect 2, cast('2008-1-15' as datetime), 1200, 2, 1union allselect 2, cast('2008-2-15' as datetime), 1100, 2, 1union allselect 2, cast('2008-3-15' as datetime), 1150, 2, 1select salespersons.salesperson, #month.[month], sum(i.invoicetotal) totaalfrom #month, (select distinct salespersonfrom #invoices) salespersons, #invoices iwhere i.salesperson = salespersons.salespersonand #month.[month] = datepart(month, i.invoicedate)group by salespersons.salesperson, #month.[month]