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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Pivot

Author  Topic 

glendcruz
Yak Posting Veteran

60 Posts

Posted - 2010-11-02 : 19:32:57
This is one of the Queries I seen on this forums a few days ago

DECLARE @V_BillingEntriesFull TABLE
(
ArrivalDate datetime,
TotalAmount money
)
insert into @V_BillingEntriesFull
select '2009/01/01', 500 union all
select '2010/02/01', 600 union all
select '2011/03/01', 750 union all
select '2009/01/01', 600 union all
select '2010/02/01', 550 union all
select '2011/03/01', 750 union all
select '2009/01/01', 4200 union all
select '2010/02/01', 100 union all
select '2011/03/01', 2140

The client wanted the output as

Month 2009 2010 .....
-----------
Jan 500
Feb 250
Mar 4200

Some one sujested to try using a Pivot.
I tried doing it myself but i just cannot get it
I am sure there are a few exceptional Gurus who can work it out.

Will be greately appreciated if any one can do it.

Thanks to all

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-11-02 : 22:14:15
[code]
select *
from (
select yr = datepart(year, ArrivalDate),
mth = datename(month, ArrivalDate),
TotalAmount
from @V_BillingEntriesFull
) d
pivot
(
sum(TotalAmount)
for yr in ([2009], [2010], [2011])
) p
[/code]

you will need to use Dynamic SQL if the number of year is not fixed and variables


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-11-03 : 04:46:34
For unknown number of years, use
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

glendcruz
Yak Posting Veteran

60 Posts

Posted - 2010-11-03 : 18:19:35
quote:
Originally posted by madhivanan

For unknown number of years, use
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail



Thanks Kitan, much appreciated for your prompt reply. I will try it out
Go to Top of Page

glendcruz
Yak Posting Veteran

60 Posts

Posted - 2010-11-03 : 20:05:48
quote:
Originally posted by glendcruz

quote:
Originally posted by madhivanan

For unknown number of years, use
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail



Thanks Kitan, much appreciated for your prompt reply. I will try it out
Yes i tried it out and it works fine.
Thanks too to Madihavan. I like your exc function , its too complicated for me

Go to Top of Page
   

- Advertisement -