Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
Hi All
I have SQL table like below

Rack  Cell  Qty
A1     X     20
A2     Y     30
A3     Z     40
B1     X     59
B2     Z     60
C1     X     70


Now my question is how I can display the table like below

   X  Y  Z
A1
A2
A3
B1
B2
C1


In original table X, Y, Z is more then one time but new table it shows only one time each

Thanks to All
Posted
Updated 1-Aug-12 2:22am
v2
Comments
Santhosh Kumar Jayaraman 1-Aug-12 6:39am    
Your expected table and the requirements you mentioned doesnt match

Try this. It is not tested so if any problem please reply.
SQL
select A.Rack,
 (select Sum(B.Qty) from tablename B  where B.Rack =A.Rack and B.Cell ='X') as 'X',
 (select Sum(B.Qty) from tablename B  where B.Rack =A.Rack and B.Cell ='Y') as 'Y',
 (select Sum(B.Qty) from tablename B  where B.Rack =A.Rack and B.Cell ='Z') as 'Z',
 Count(A.Rack)
from tablename A
group by A.Rack
 
Share this answer
 
v5
Comments
IndrajitDasgupat 2-Aug-12 1:14am    
Yes Sir it is working but if A1 has x,y,z three value then it shows three rows but I need in one row and if you little explain how it works then it will help me lot in future.
Thanks a Lot
pradiprenushe 2-Aug-12 1:45am    
Can you explain this requirement?What i understand is
Rank Cell
A1 X,Y,Z
After that what you want?
IndrajitDasgupat 2-Aug-12 2:32am    
My original table is like below
Rack cell qty
A1 X 20
A1 Y 30
A1 Z 40
B1 X 70
B1 Y 60
C1 Z 34
C1 z 22

Now my table should display like below
Rack X Y Z
A1 20 30 40
B1 70 60 Null
C1 Null Null 56

Thanks
pradiprenushe 2-Aug-12 2:39am    
What ouput currently it is giving?
IndrajitDasgupat 2-Aug-12 2:48am    
Currently it is giving like below
Rack X Y Z
A1 20 30 40
A1 20 30 40
A1 20 30 40
B1 70 60 Null
B1 70 60 Null

So A1 it should come one line and B1 also should also in one line
and moreover C1 should display like below
C1 Null Null 56
Thanks
Depends on the version of SQL Server you are using. For SQL 2005 and later you want to use PIVOT.

For more details see:
http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server-2005/[^]

This way you are not hardcoding the number of cells - if that grows the table of results automatically gets an extra column. Very similar to the CROSSTAB query in MS Access.

Alistair
 
Share this answer
 
SQL
select distinct A.Rack,
 (select B.Qty from temp B  where B.Rack =A.Rack and B.Cell like '%X%') as 'X',
 (select B.Qty from temp B  where B.Rack =A.Rack and B.Cell like '%Y%') as 'Y',
 (select B.Qty from temp B  where B.Rack =A.Rack and B.Cell like'%Z%') as 'Z'
from temp A
 
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