Click here to Skip to main content
16,016,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys ,

i have 2 tables

Table1

Name Access Code
A 1
A 2
A 3
A 4
B 2
B 3
C 1

Table2

Name phone email
A 1234 test@test.com
B 2233 E@email.com
C 5566 F@gmail.com


Now Guys i want some result like

Name phone email AccessCode
A 1234 test@test.com 1,2,3,4
B 2233 F@email.com 2,3
C 5566 F@gmail.com 1

or they can be in multiple columns too, like

Name phone email AccessCode Column2 Columns3 Column4
A 1234 test@test.com 1 2 3 4
B 2233 F@email.com 2 3
C 5566 F@gmail.com 1


For this i tried the STUFF query with xml path also.


i want to join those 2 tables and get a result something like mentioned above please help !!


i tried like this

SELECT name,phone, email
SUBSTRING((SELECT DISTINCT + accesscode FROM T2 INNER JOIN T1 ON t1.name = t2.name
FOR XML PATH('')),2,20000) AS MyColumn
From T2

Help appreciated !!
Posted
Updated 11-Dec-14 22:50pm
v2

DEMO[^]
SQL
CREATE TABLE Table2 
	(
     name varchar(20), 
     phone varchar(20), 
     email varchar(20)
    );

CREATE TABLE Table1
	(
     name varchar(20), 
     accesscode varchar(20)
    );
 
 
INSERT INTO Table2
(name, phone, email)
VALUES
('A' ,'1234', 'test@test.com'),
('B ' ,'2233' ,'E@email.com'),
('C ' ,'5566' ,'F@gmail.com');
 
INSERT INTO Table1
(name, accesscode)
VALUES
('A' ,'1'),
('A' , '2'),
('A' , '3'),
('A' , '4'),
('B' , '2'),
('B' ,'3'),
('C' , '1')


SQL
SELECT
      m.name
    , m.phone
    , m.email
    , accesscode = STUFF((
          SELECT ',' + md.accesscode
          FROM Table1 md
          WHERE m.name = md.name
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Table2 m


refer :
http://sqlandme.com/2011/04/27/tsql-concatenate-rows-using-for-xml-path/[^]
https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/[^]
How to make a query with group_concat in sql server[^]
 
Share this answer
 
v3
Comments
Maciej Los 12-Dec-14 5:49am    
+5
DamithSL 12-Dec-14 8:04am    
thank you, maciej
Sanman Marathe 12-Dec-14 8:59am    
Thank you, That was very helpful ! Cheers ! !!!!
 
Share this answer
 
Comments
DamithSL 12-Dec-14 8:04am    
5wd!
Maciej Los 12-Dec-14 8:05am    
Thank you, Damith ;)
Sanman Marathe 12-Dec-14 9:00am    
Thank you !!!! Those were helpful to get more knowledge !!!!!
Maciej Los 12-Dec-14 10:40am    
You're very welcome.
Please, accept all valuable solutions (green button).
Sanman Marathe 26-Dec-14 5:59am    
sure !!!

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