SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Add sum to this dynamic sql pivot.
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

sapator
Constraint Violating Yak Guru

Greece
422 Posts

Posted - 02/12/2014 :  00:14:46  Show Profile  Reply with Quote
Hi.
I have created a pivot dynamically but i also want to add a sum on qtt (is integer) that i cannot do it.If i put a sum after 'SELECT [description],' + @cols + ' , it will say qtt column not found, if i group by after "x" and before pivot is still does not work.
Any thoughts?


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME([date]) 
                    from  Table_1
                    group by [date]
                    order by [date]
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT [description],' + @cols + '  
            from 
            (
              SELECT 
                 a.[description],
                 a.[date],
                 a.qtt
                -- ,sum(a.qtt) as total
              FROM Table_1 a      
               group by [date],[description],qtt
            ) x 
            pivot 
            (
                max(qtt)
                for [date] in (' + @cols + ') 
            ) p ' 

execute sp_executesql @query;

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 02/12/2014 :  00:20:15  Show Profile  Reply with Quote
i think you should use this method instead if you want to use multiple pivot

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

sapator
Constraint Violating Yak Guru

Greece
422 Posts

Posted - 02/12/2014 :  01:23:39  Show Profile  Reply with Quote
I'll have a look tomorrow.Does this support sum of columns?
Thanks.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 02/12/2014 :  05:26:11  Show Profile  Reply with Quote
quote:
Originally posted by sapator

I'll have a look tomorrow.Does this support sum of columns?
Thanks.


yes it will

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.48 seconds. Powered By: Snitz Forums 2000