sqlsql-server-2008duplicates

Removing Duplicate Rows in Employee Demographic Data Pull


I am doing a data pull to get some demographic information on employees.
I had an issue with missing employees because not everyone has a phone number (I don't know why)

Now I have duplicates because some people have a primary and not-primary phone number.
They can be listed as mobile, home, work, etc... What I want is if the employee has a primary phone number to list it, but if they don't have as number at all I want it to be listed as "N/A".


Solution

  • Is very hard give you a solution without having a schema.
    So I will try to teach you how do it using CTE Common Table Expressions

    SQL FIDDLE DEMO

    In the fiddle you can select just the code inside the WITH to see the partial result.

    That query get you the valid phone inside that date range. User1 have data User2 doesnt

    with current_phone as (
       SELECT u.name, p.*
       FROM 
           users u 
       left join phone p 
           on u.user_id = p.user_id
           and GETDATE() BETWEEN FromDate and ToDate
    )
    SELECT name, CASE 
                     WHEN phone is null then 'NA'
                     ELSE phone
                 END as phone
    FROM current_phone
    

    The idea is you do small calculation in the CTE and then join the result with the main table. Hope that help you find your solution.

    You also can update the sqlFiddle with a better schema for your case and let me know.