SQL Query aggregate phone numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EduardM
    New Member
    • Nov 2009
    • 1

    SQL Query aggregate phone numbers

    Hi, i have a question, imagine that i have a table with names and phone numbers, like this:

    Name | Phone
    Jack | 2457349843
    Jack | 9347842344
    Mary | 4324324423
    John | 3123123123
    John | 43243244324

    I want a query that returns something like this

    Name | Phone
    Jack | 2457349843, 9347842344
    Mary | 4324324423
    John | 3123123123, 43243244324

    Thanks in advance, i really need this.
  • nbiswas
    New Member
    • May 2009
    • 149

    #2
    Solution to Aggregate Phone Numbers

    Try this(Sql Server 2005+)
    -- Table declarations with sample data
    Code:
    declare @t table(name varchar(50),phone bigint)
    insert into @t 
    	select 'Jack', 2457349843 union all select 'Jack', 9347842344 union all
    	select 'Mary', 4324324423 union all
    	select 'John', 3123123123 union all select 'John', 43243244324
    --Program Starts
    Code:
    select name,LEFT(Phone,LEN(Phone) -1) as Phone from (
    select t2.name,
    		( 
    			select cast(phone as varchar(max)) + ','
    			from @t t1
    			where t1.name = t2.name
    			for XML path('')
    		) as Phone
    from @t t2
    group by t2.name)X(name,Phone)
    Output
    ----------

    name Phone
    Code:
    Jack	2457349843,9347842344
    John	3123123123,43243244324
    Mary	4324324423
    Last edited by nbiswas; Nov 23 '09, 04:39 AM. Reason: Improved formatting

    Comment

    Working...