Can anyone solve the SQL puzzle ?

  • A puzzle for SQL Masters !!!

     

    Table1
    idName
    1X
    2Y
    3Z
    4A
    5C
    6x

    Table2
    idName
    1A
    2B
    4B

    Table3
    idName
    1P
    5C

     

    Take Id as integer and Name as varchar in all three tables

    Result should be as below

     

    idName
    1P
    2B
    3Z
    4B
    5C
    6x

     

    Good luck!!

    Regards,

    Sandeep

  • Here's my quick and dirt solution, excluding the table creation and inserts code...

     

    select

    t1.id,

    Name = case

    when t3.id is not null then t3.[Name]

    when t2.id is not null then t2.[Name]

    else t1.[Name] end

    from Table1 t1

    left join Table2 t2 on t1.id = t2.id

    left join Table3 t3 on t1.id = t3.id

     

     


    Td Wilson

  • Hi ,

    Excellent Question and very good answer by Td Wilson ...

    Good One Boss..............

     

    Regards ,

    Amit Gupta...

     

     

  • Same result may be achieved with a little bit simpler query:

    select t1.id, COALESCE (t3.[Name], t2.[Name], t1.[Name]) as Name

    from Table1 t1

    left join Table2 t2 on t1.id = t2.id

    left join Table3 t3 on t1.id = t3.id

    _____________
    Code for TallyGenerator

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

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