Click here to Skip to main content
15,879,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
Acc   Plan
121  A
131  B
141  C
121  B
145  D
131  A
141  A
190  R
200  S
121  A



I want result like


SQL
acc	Plan
121	A-2,B -1
131	B,A
141	A,C
145	D
190	R
200	S
Posted
Comments
Kornfeld Eliyahu Peter 3-Aug-15 3:22am    
What have you tried?[^]
(Hint: No. And the reason is that you output is not consistent...
Once you attach a counter to 'Plan' values even it is 1, but on the other lines you do not...)
Tryingtobeageek 3-Aug-15 3:39am    
hi ... For example acc 121 is having two 'A' plan, that result i required as 'A - 2'
Suvendu Shekhar Giri 3-Aug-15 3:48am    
Do you expect output to be-
acc plan
-----------------
121 A-2,B-1
131 A-1,B-1
141 A-1,C-2
145 D-1
190 R-1
200 S-1

?

1 solution

You may use STUFF Function to achieve this, below script should give you proper result

SQL
declare @tbl table(Acc int,  [Plan1] nchar)

insert into @tbl
select 121,'A'
UNION ALL
SELECT 131,'B'
UNION ALL
SELECT 141,'C'
UNION ALL
SELECT 121,'B'
UNION ALL
SELECT 145,'D'
UNION ALL
SELECT 131,'A'
UNION ALL
SELECT 141,'A'
UNION ALL
SELECT 190,'R'
UNION ALL
SELECT 200,'S'
UNION ALL
SELECT 121,'A'


select Acc,
STUFF((Select ',' + cast(T1.Plan1 + cast(Count(1) as nvarchar) as nvarchar)
FROM @tbl T1
WHERE T1.Acc = T.Acc
GROUP BY T1.Plan1 for xml path('')),1,1,'')
FROM @tbl T
group by Acc


Regards,
Sujay C.
 
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