Click here to Skip to main content
15,904,153 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Current showing data are:
col1 col2  col3  col4
1     AA    A001  300
2     AA    B001  200
3     AA    C001  450
4     BB    A001  230
5     BB    E001  300
6     CC    A001  200
7     CC    A002  300
...   ...   ...   ...
...   ...   ...   ...
...   ...   ...   ...



The result will be:

      A001 A002 B001 C001 E001 ...
AA    300  0    200  450  0    ...
BB    230  0    0    0    300  ...
CC    200  300  0    0    0    ...
...   ...  ...  ...  ...  ...  ...
...   ...  ...  ...  ...  ...  ...


I have above problem. So, pls help!

P.S: AA,BB,CC,... and also A001,A002,B0001,... can be grown. I wish the result be "dynamically increase rows and columns".
Posted
Updated 10-Jun-11 3:19am
v3
Comments
z4rk 10-Jun-11 5:09am    
But the A001, A002 are variable and growing. I want to say is "dynamically".

There are couple of ways.

Pivoting data in SQL Server[^]
 
Share this answer
 
Comments
z4rk 10-Jun-11 9:17am    
the data, A001,A002,... and AA,BB,CC,... can grow vertically and horizontally.
i can't handle when rows and columns are in dynamic. btw, thanks.
Espen Harlinn 10-Jun-11 12:16pm    
My 5
SQL
create table #temptab
(
col1 int ,
col2  varchar(10),
col3  varchar(10),
col4 int
)
insert into #temptab
select 1,	  'AA',    'A001',  300
insert into #temptab
select 2,     'AA',    'B001',  200
insert into #temptab
select 3,     'AA',    'C001',  450
insert into #temptab
select 4,     'BB',    'A001',  230
insert into #temptab
select 5,     'BB',    'E001',  300
insert into #temptab
select 6,     'CC',    'A001',  200
insert into #temptab
select 7,     'CC',    'A002',  300
select COL2, ISNULL([A001],0),ISNULL([A002],0),ISNULL([B001],0),ISNULL([C001],0),ISNULL([E001],0) from
(select col2, col3, col4 
from #temptab) tab1
PIVOT (max(col4) FOR COL3 IN([A001],[A002],[B001],[C001],[E001]) ) TAB2

I think this should give u a clear picture....
 
Share this answer
 
v2
Comments
z4rk 10-Jun-11 5:34am    
thanks.
You need to create a PIVOT table: MSDN has instructions and a small example: Pivot table[^]
 
Share this answer
 
Comments
z4rk 10-Jun-11 5:34am    
thanks u.

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