Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Pivot statement with Dynamic SQL and totals columns

Posted on 2010-08-20
3
438 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
ID: 33484236

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
ID: 33484287
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
ID: 33484382
If this is in an SP, no you don't have to drop it.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

856 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