Remove duplicates from Multiple colums please help me

  • Input:

    Table1

    D1 D2 D3 D4 D5

    1 4 4 2 3

    Excepted output

    Table2

    D1 D2 D3 D4 D5

    1 4 2 3

    I have to fetch the values from the Table1 and insert into Table2 in the excepted output..

    Please some one help me to reslove the problem?

  • Insert into Table 2 the results from this query:

    WITH SampleData (D1, D2, D3, D4, D5) AS

    (

    SELECT 1, 4, 4, 2, 3

    )

    SELECT D1=MAX(CASE WHEN rn1=1 THEN D END)

    ,D2=MAX(CASE WHEN rn1=2 THEN D END)

    ,D3=MAX(CASE WHEN rn1=3 THEN D END)

    ,D4=MAX(CASE WHEN rn1=4 THEN D END)

    ,D5=MAX(CASE WHEN rn1=5 THEN D END)

    FROM

    (

    SELECT D, n, rn1=ROW_NUMBER() OVER (ORDER BY n)

    FROM

    (

    SELECT D, n, rn=ROW_NUMBER() OVER (PARTITION BY D ORDER BY n)

    FROM SampleData a

    CROSS APPLY

    (

    SELECT 1,D1 UNION ALL SELECT 2,D2 UNION ALL SELECT 3,D3

    UNION ALL SELECT 4,D4 UNION ALL SELECT 5,D5

    ) b (n, D)

    ) a

    WHERE rn=1

    ) a;


    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 2 posts - 1 through 2 (of 2 total)

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