Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Pivot Table Month Name Order

Author  Topic 

gecew
Starting Member

10 Posts

Posted - 2013-12-02 : 09:43:27
how to order by month name query returns Dec13,Mar14,Jan14,Nov13 .. etc
but i want to Nov13,Dec13,Jan14,Mar14 ... etc

declare @cols as varchar(max),
@query as varchar(max)
set @cols =STUFF((select ','+QUOTENAME(tb3.month) FROM
( select distinct (DATENAME(MONTH,dtDate)+''+CONVERT(varchar(5),YEAR(dtDate)) ) as month
from tableA) tb3

FOR XML PATH(''), TYPE ).value('.','NVARCHAR(MAX)'),1,1,'')
set @query ='SELECT '+@cols +' from (SELECT DATENAME(MONTH,dtDate) + CONVERT(varchar(5),YEAR(dtDate)) as month,Price FROM tableA ) tb
pivot ( sum(Price) for monthin('+@Cols+')) p
'
exec(@query)

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-02 : 10:05:05
[code]
declare @cols as varchar(max),
@query as varchar(max)
set @cols =STUFF((select ','+QUOTENAME(tb3.month) FROM
( select distinct (DATENAME(MONTH,dtDate)+''+CONVERT(varchar(5),YEAR(dtDate)) ) as month,YEAR(dtDate) * 100 + MONTH(dtDate)AS MonthNo
from tableA) tb3
ORDER BY MonthNo
FOR XML PATH(''), TYPE ).value('.','NVARCHAR(MAX)'),1,1,'')
set @query ='SELECT '+@cols +' from (SELECT DATENAME(MONTH,dtDate) + CONVERT(varchar(5),YEAR(dtDate)) as month,Price FROM tableA ) tb
pivot ( sum(Price) for monthin('+@Cols+')) p
'
exec(@query)
[/code]

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

gecew
Starting Member

10 Posts

Posted - 2013-12-02 : 10:35:09
@Visakh16 thx
Go to Top of Page

gecew
Starting Member

10 Posts

Posted - 2013-12-03 : 03:56:13
i can't grand total row how do it
Go to Top of Page

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2013-12-03 : 04:20:17
I would do grand totals in the reporting layer rather than here.
Go to Top of Page

gecew
Starting Member

10 Posts

Posted - 2013-12-03 : 04:33:46
i use datatable compute and works perfect thx
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-03 : 06:22:22
quote:
Originally posted by gecew

i can't grand total row how do it


this is the way to do it within PIVOT just if you're interested


http://visakhm.blogspot.in/2012/04/display-total-rows-with-pivotting-in-t.html


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

- Advertisement -