PIVOT Command in SQL Server

There are many cool new features in SQL Server 2005. For example, “Extended Stored Procs“ written in .NET with connections via SqlContext. How cool is this!?!? Check out the new PIVOT command in T-SQL for SQL Server 2005…

declare @sales table
(
[Year] int,
Quarter char(2),
Amount float
)

insert into @sales values(2001, ‘Q1’, 70)
insert into @sales values(2001, ‘Q1’, 150)
insert into @sales values(2002, ‘Q1’, 20)
insert into @sales values(2001, ‘Q2’, 15)
insert into @sales values(2002, ‘Q2’, 25)
insert into @sales values(2001, ‘Q3’, 50)
insert into @sales values(2002, ‘Q3’, 20)
insert into @sales values(2001, ‘Q4’, 90)
insert into @sales values(2001, ‘Q4’, 80)
insert into @sales values(2002, ‘Q4’, 35)

select * from @sales
pivot
(
sum(Amount)
for Quarter
in (Q1, Q2, Q3, Q4)
as p

Year| Q1  |Q2  |Q3 |Q4
———–| ——— |——- |——- |——–
2001| 220 |15  |50 |170
2002| 20  |25  |20 |35

(2 row(s) affected)

Advertisements

2 thoughts on “PIVOT Command in SQL Server

  1. The next time I read a blog, I hope that it doesnt disappoint me as considerably as this 1. I mean, I know it was my option to read, but I truly thought youd have some thing interesting to say. All I hear is actually a bunch of whining about something that you could fix in case you werent too busy looking for attention.

    Youth NFL Jerseys

  2. I just want to say I am all new to blogging and actually savored you’re web-site. Very likely I’m want to bookmark your site . You surely come with impressive writings. Many thanks for sharing your web site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s