Solved

Pivot statement with Dynamic SQL and totals columns

Posted on 2010-08-20
3
434 Views
Last Modified: 2012-05-10
The atteached code, supplied by an EE Expert works great.

The data is output as:
rep     January     February     etc
myrep  1000          1250          etc

Question...
Is there a way to add a totals column and if possible an average per month column?

New output desired...
rep     January     February     etc    Totals     AVG
myrep  1000          1250          etc     2250       1125
SELECT  v.rep,    

		Sum(v.[Gross Rev]) as GrossRev,     

		DATENAME(month, v.Funded) as Mth  ,  

		month(v.Funded) as MthI    

Into #temp    

FROM	CRMPROD_01.dbo.v_P_Reporting v    

WHERE	v.Funded is not null     

		and	v.Status <> 'Closed'     

		and	(YEAR(v.Funded) = YEAR(getdate()))     

		and	(MONTH(v.Funded) > MONTH(getdate())-@)    

Group by rep, v.Funded    

ORDER BY v.rep, month(v.Funded)  

  

--Create Dynamic SQl and Pivot   

declare @sql varchar(4000)  

declare @columns varchar(8000)    

  

select @columns = coalesce(@columns+',','') + '[' + Mth + ']'  

from #temp  

group by Mth, MthI  

order by MthI  

   

set @sql = '  

    SELECT [rep], ' + @columns + '  

    FROM    

    (SELECT [rep], [GrossRev], [Mth] as Mth from #temp) src  

     PIVOT  

    (Sum ([GrossRev]) FOR Mth IN (' + @columns + ') ) AS pvt'  

   

EXEC (@sql)  

  

Drop table #temp

Open in new window

0
Comment
Question by:lrbrister
  • 2
3 Comments
 
LVL 58

Accepted Solution

by:
cyberkiwi earned 500 total points
Comment Utility

SELECT  v.rep,    

		Sum(v.[Gross Rev]) as GrossRev,     

		DATENAME(month, v.Funded) as Mth  ,  

		month(v.Funded) as MthI    

Into #temp    

FROM	CRMPROD_01.dbo.v_P_Reporting v    

WHERE	v.Funded is not null     

		and	v.Status <> 'Closed'     

		and	(YEAR(v.Funded) = YEAR(getdate()))     

		and	(MONTH(v.Funded) > MONTH(getdate())-@)    

Group by rep, v.Funded    

ORDER BY v.rep, month(v.Funded)  

  

--Create Dynamic SQl and Pivot   

declare @sql varchar(4000)  

declare @columns varchar(8000)    

declare @totals varchar(8000)

declare @averages varchar(8000)

  

select	@columns = coalesce(@columns+',','') + '[' + Mth + ']',

		@totals  = coalesce(@totals+'+','') + 'isnull([' + Mth + '],0)',

		@averages  = coalesce(@averages+'+','') + 'isnull(abs(sign([' + Mth + '])),0)'

from #temp

group by Mth, MthI  

order by MthI



set @sql = '  

    SELECT [rep], ' + @columns +

		',[Total]=' + @totals +

		',[AVG]=1.0*(' + @totals + ')/isnull(nullif(' + @averages + ',0),0)

    FROM    

    (SELECT [rep], [GrossRev], [Mth] as Mth from #temp) src  

     PIVOT  

    (Sum ([GrossRev]) FOR Mth IN (' + @columns + ') ) AS pvt'  

   

EXEC (@sql)  

  

Drop table #temp

Open in new window

0
 

Author Closing Comment

by:lrbrister
Comment Utility
cyberkiwi
Wonderful...thanks.

If I can ask a quick follow-up...'

If this is in  astored procedure that I'll call from my VB code...is it necessary to have the "drop table #temp" at the end...or will that automatically drop after the SP executes?
0
 
LVL 58

Expert Comment

by:cyberkiwi
Comment Utility
If this is in an SP, no you don't have to drop it.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how the fundamental information of how to create a table.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now