Click here to Skip to main content
15,894,291 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have table such as
Order_Id	InventoryId	ItemType	total
1		5		Orange		5000
1		4		Apple		3000
2		1		Mango		3400
2		5		Orange		1700

If i pass order id '1' i need record like
Orange  Apple
5000    3000


If i pass order id '2' i need record like
Mango   Orange
3400    1700


how can i achieve this can any one help for the same.
Posted

SQL
Declare @OrderId int = 2

If((select distinct 1 from Tem where Order_Id = @OrderId)=1)
begin
select Orange,Apple,Mango from
(select Order_Id,ItemType,total From Tem Where Order_Id = @OrderId)u
pivot(sum(total) for ItemType in ([Orange],[Apple],[Mango])) as pvt
end
 
Share this answer
 
Use Dynamic Query with Pivot... try some thing like this...
SQL
Declare @Id Int, @Sql varchar(400),@Cols varchar(40)
Create Table #Temp
		(
		Order_Id Int,
		InventoryId	 Int,
		ItemType Varchar(40),
		total Int
		)

Insert into #Temp
Values(1,5,'Orange',5000),(1,4,'Apple',3000),(2,1,'Mango',3400),(2,5,'Orange',1700)

Set @Id=2  -- if you want records for id 1 set @Id=1

Set @Cols= Stuff((Select Distinct '],['+ItemType From #Temp Where Order_Id=@Id 
           for Xml Path(''),Type).value('.','VARCHAR(Max)'), 1, 2,'')+']'

Set @Sql= 'Select '+@Cols + 'From (Select ItemType,total From #Temp Where Order_Id='
          + Cast(@Id as Varchar) +')st pivot (Sum(total) For ItemType in ('
          + @Cols + '))Pvt'

Exec(@Sql)

Drop Table #Temp 
 
Share this answer
 
v3
Comments
Raja Sekhar S 30-Sep-13 4:22am    
Did it solve your problem..?
The following works with catalogs (when there is only one row for each fruit

SQL
select 
        max(case when ItemType = 'Orange' then Total end) as Orange
        , max(case when ItemType = 'Apple' then Total end) as Apple
        , max(case when ItemTpe = 'Mango' then Total end) as Mango
//...and so on

FROM Inventory


Should there be many rows for each fruit, use SUM instead of MAX.

There is no straight way (that I know of) to avoid hard-coding every event, unless you use something like C# or VB or C++ to build your query string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900