Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have the table like this

name group
aaa A
aaa B
aaa A
aaa C

I want to get the output in the format of

name A B C
aaa 2 1 1

how to get this ,any suggestion pls
Posted

Use PIVOT - UNPIVOT

Using PIVOT and UNPIVOT[^]
Pivoting data in SQL Server[^](Alternate ways)
 
Share this answer
 
Comments
prabhatsp 12-Nov-13 2:39am    
I am having only 2005 sql server
Thanks7872 12-Nov-13 2:41am    
http://msdn.microsoft.com/en-us/library/ms177410(v=sql.90).aspx
thatraja 12-Nov-13 2:46am    
Change the version by clicking the link 'Other versions' there.
And did you check the 2nd link in my answer? There're alternatives.
prabhatsp 12-Nov-13 3:57am    
it works but it shows like
name1 A B C
aaa A B C

my query is
select name1,'A' as A,'B' as B,'C' as C from (select id,name1,group from table1) p
pivot(count(id) for group in (['A'],['B'],['C'])) As pvt order by name1
Try below Soluton...
SQL
DECLARE @temp TABLE (NAME CHAR(3), GROUP1 CHAR(2))

INSERT INTO @temp (NAME, GROUP1)
VALUES 
     ('AAA', 'A'),     
     ('AAA', 'B'),
     ('AAA', 'A'),
     ('AAA', 'C')
 SELECT
      NAME
    , A = COUNT(CASE WHEN GROUP1 = 'A' THEN 1 END)
    , B = COUNT(CASE WHEN GROUP1 = 'B' THEN 1 END)
    , C = COUNT(CASE WHEN GROUP1 = 'C' THEN 1 END)
FROM @temp
GROUP BY NAME
 
Share this answer
 
v2
Comments
prabhatsp 12-Nov-13 6:53am    
thank u ,I got the output
prashant patil 4987 12-Nov-13 7:03am    
@prabhat- Most Welcome.
Have a great Future ahead..
HAppy Coding ...
it can be done through pivot table.
It is designed for the purpose you are searching
 
Share this answer
 
Here is a pivot approach :

SQL
declare @data table (name varchar(50),[group] varchar(50))

insert into @data (NAME, [GROUP])
values  ('AAA', 'A'), ('AAA', 'B'), ('AAA', 'A'), ('AAA', 'C'), ('BBB', 'A'), ('BBB', 'B'), ('BBB', 'B')

select name, A,  B, C
from (select name, [group], count([group]) count from @data group by name, [group]) src
pivot (sum([count]) FOR [group] in ( [A], [B], [C])) pvt


Good Luck
 
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