CREATE TABLE dbo.QuoteMaster ( QuoteDate date, Client varchar(100), NumQuotes int) CREATE TABLE dbo.CancellationMaster (CancelDate Date, Client varchar(100), Problem varchar(100), Qty int)OK, now for the stored procedure. It's at the end of this post at the bottom. I'm actually going to cover this more in detail as a blog post (from time to time I get questions about dynamic sql).
;WITH PIVOTCTE as (select QuoteDate as ActivityDate, Client, 'Quotes' as ActionType, NumQuotes as Qty FROM dbo.QuoteMaster UNION SELECT CancelDate as ActivityDate, Client, Problem as ActionType, Qty from dbo.CancellationMaster) SELECT ActivityDate, Client, [Quotes],[Declined at begining],[No Credit Card],[Not Ended] FROM PIVOTCTE pivot ( SUM(Qty) for ActionType in ([Quotes],[Declined at begining],[No Credit Card],[Not Ended])) TEMPLISTSo....finally, here's the procedure you can use. This will read the data and build the necessary pivot statement, and execute it using dynamic sql.
CREATE PROCEDURE dbo.DynamicPivotExample as begin -- Strings to build, to execute dynamically DECLARE @ActionSelectString nvarchar(4000) , @SQLPivotQuery nvarchar(4000) -- get a unique list of the possible Problem values ;WITH ListTempCTE as (SELECT 'Quotes' AS ActionType , 1 as OrderNum -- hard wire this one UNION SELECT DISTINCT Problem as Actiontype, 2 as OrderNum FROM CancellationMaster ) -- build the ActionString for the problem values . This will look like the following -- [Quotes],[Declined at begining],[No Credit Card],[Not Ended] SELECT @ActionSelectString = stuff ( ( select ',[' + cast(ActionType as varchar(100)) + ']' from ListTempCTE ORDER BY OrderNum, ActionType for xml path('') ), 1, 1, '') -- Now build the entire query....which reads the quote master and the cancellationmaster....does a UNION to load them all together -- so that we can have a basic PIVOT across all possible values SET @SQLPivotQuery = ';WITH PIVOTCTE as (select QuoteDate as ActivityDate, Client, ''Quotes'' as ActionType, NumQuotes as Qty FROM dbo.QuoteMaster UNION SELECT CancelDate as ActivityDate, Client, Problem as ActionType, Qty from dbo.CancellationMaster) ' set @SQLPivotQuery = @SqlPivotQuery + ' SELECT ActivityDate, Client, ' + @ActionSelectString + ' FROM PIVOTCTE pivot ( SUM(Qty) for ActionType in (' + @ActionSelectString + ')) TEMPLIST' EXEC sp_executesql @SqlPivotQuery endAnd then to execute it...