Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 3147 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > SQL Server > Pivoting in Sql Server 2000 ...
Niladri.Biswas

Pivoting in Sql Server 2000

 Code Snippet posted by: Niladri.Biswas | Posted on: 6/18/2012 | Category: SQL Server Codes | Views: 393 | Status: [Member] | Points: 40 | Alert Moderator   
Ads

Given a table as under

OrderId	OrderName	WillShipToDeptId

1 A 1
1 B 2
2 X 1
2 Y 2


The expected output is

OrderId	FirstOrder	SecondOrder	FirstOrderType	SecondOrderType

1 A B 1 2
2 X Y 1 2


Solution

First let us create the DDL to set up the enviroment

declare @t table(OrderId int,OrderName Varchar(10),WillShipToDeptId int) 

Insert into @t
values(1,'A',1),(1,'B',2),(2,'X',1),(2,'Y',2)
select * From @t


The solution is as under

select 

OrderId,
max(case WillShipToDeptId when 1 then OrderName end) as FirstOrder,
max(case WillShipToDeptId when 2 then OrderName end) as SecondOrder,
1 as FirstOrderType,
2 as SecondOrderType
from @t
group by OrderId


Best Regards,
Niladri Biswas
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/18/2013 5:37:31 PM