Flatten results from a SQL table

  • Hi all,

    I have a table that contains phone number and email addresses, this table was created in a way that every time a new phone number or email address is created, for the same client, it creates a new row.

    I need a way to get a report that shows all the phone numbers and email addresses per client.

    UniqID, UniqClient, PhoneNumber, EmailWeb

    3, 66, 4164445555

    5, 66, , fstest1@test.com

    In this example, the first row contains a phone number and the second row the email address (for the same client - 66).

    I need to get one row with phone number and email address.

    Any help is truly appreciated.

    Thank you very much.

  • Hi,

    This is one simple solution (didn't count on the performance):

    create table CustInfo

    (UniqId int identity(1,1),

    UniqClient int,

    PhoneNumber varchar(20),

    EmailWeb varchar(50)

    )

    insert into CustInfo (UniqClient,PhoneNumber,EmailWeb)

    values(66,'4164445555',''),(66,'','fstest1@test.com')

    select top(1) t.UniqClient,

    (select top (1) t2.PhoneNumber from dbo.CustInfo t2 where t2.UniqClient = t.UniqClient and len(isnull(t2.PhoneNumber,'')) > 0) as PhoneNumber,

    (select top (1) t3.EmailWeb from dbo.CustInfo t3 where t3.UniqClient = t.UniqClient and len(isnull(t3.EmailWeb,'')) > 0) as EmailWeb

    from dbo.CustInfo t

    where t.UniqClient = 66

    You can add an ORDER BY if you need a reason for.

    Regards,

    Igor

    Igor Micev,My blog: www.igormicev.com

  • Perhaps this?

    WITH SampleData (UniqID, UniqClient,PhoneNumber,EmailWeb) AS

    (

    SELECT 3, 66,'4164445555','' UNION ALL SELECT 5, 66,'','fstest1@test.com'

    )

    SELECT UniqClient, PhoneNumber=MAX(PhoneNumber), EmailWeb=MAX(EmailWeb)

    FROM SampleData

    GROUP BY UniqClient;


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply