select rows with same id and some other value in another column for that id

  • Hello!

    Example

    If both rows have same ID and  has Type ='Alias' then output should be as below:

    +----------+-------+-------+

    | ID            |Name | Type |

    +----------+-------+-------

    | 1               | abc    |Alias  |

    | 1               | ef       | AA    |

    | 2               | AA    | AB    |

    +----------+-------+--------

    Need Ouput:

    +----------+-------+-------+

    | ID            | Name | Alias |

    +----------+-------+-------+

    | 1               | abc      | ef     |

    | 2               | AA       | AB  |

    +----------+-------+--------

     

    Thanks in advance.

  • You could divide the rows using two queries: one above and one below UNION ALL. Above SELECT ID's with [type]='Alias' and below SELECT ID's without any 'Alias'.  You could assign the new alias using OUTER APPLY SELECT TOP(1) and without ORDER BY to randomly select names

    with data_cte as (
    select *
    from (values (1, 'abc', 'Alias'),
    (1, 'ef', 'AA'),
    (2, 'AA', 'AB')) v(id, [name], [type]))
    select d.id, d.[name], oa.[name] Alias
    from data_cte d
    outer apply (select top(1) dd.[name]
    from data_cte dd
    where dd.id=d.id
    and dd.[type]<>'Alias') oa([name])
    where d.[type]='Alias'
    union all
    select *
    from data_cte d
    where not exists (select 1
    from data_cte dd
    where dd.id=d.id
    and dd.[type]='Alias');

    Aus dem Paradies, das Cantor uns geschaffen, soll uns niemand vertreiben können

  • This was removed by the editor as SPAM

  • Shezsa wrote:

    That is battling. I was stunned by your affiliation. I'm happy to see a particularly subject. Altruisticly go to my blog and read it.

    Spam incoming .....

  • DesNorton wrote:

    Shezsa wrote:

    That is battling. I was stunned by your affiliation. I'm happy to see a particularly subject. Altruisticly go to my blog and read it.

    Spam incoming .....

    Someone is running some really silly AI SPAM generators.  They need to get their money back. 😀

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • This was removed by the editor as SPAM

Viewing 6 posts - 1 through 5 (of 5 total)

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