1

Please help, I'm unable to figure out a SQL query. I'm trying to filter data in a table so that it doesn't contain duplicates. I also want to filter the results using the following:

  1. Distinct Name only

  2. The query should first check the most complete record on the duplicates (the row with less nulls) and return it.

  3. If the nulls are equal. It should take the one with the max date (the one with the most recent date)

Some sample data:

| Name   | Surname | address | date created | Nullcount |
| prince | jordan  | NULL    | 23/06/2016   |     1     |
| prince | jordan  |  NULL   | NULL         |     2     | 
| Mary.  | Smith   | 113 end | 23/06/2016   |     0     |
| Mary.  | Smith.  | 114 end | 25/06/2016   |     0     |
| John   | Keller. | 106 end | 23/06/2016   |     0     |
| John   | Keller. | NULL.   | 26/06/2016   |     1     |

My expected results

| Name   | Surname   | address  | date created | Nullcount |
| prince | jordan    | NULL     | 23/06/2016   |     1     |
| Mary.  | Smith.    | 114 end  | 25/06/2016   |     0     |
| John   | Keller.   | 106 end  | 23/06/2016   |     0     |
1
  • 1
    Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar to nicely format and syntax highlight it!
    – marc_s
    Jun 5, 2016 at 20:29

1 Answer 1

0

Query

WITH X AS (
    Select * 
      , NullCount = CASE WHEN Name        IS NOT NULL THEN 0 ELSE 1 END
                  + CASE WHEN Surname     IS NOT NULL THEN 0 ELSE 1 END
                  + CASE WHEN [address]   IS NOT NULL THEN 0 ELSE 1 END
                  + CASE WHEN DateCreated IS NOT NULL THEN 0 ELSE 1 END
    FROM TableName 
), Y AS (
SELECT *
    ,ROW_NUMBER() OVER (PARTITION BY Name, Surname 
                        ORDER BY NullCount , DateCreated DESC)  rn
FROM X 
)
SELECT Name ,  Surname , [address] , DateCreated
FROM Y
WHERE rn = 1

Result Set

╔════════╦═════════╦═════════╦═════════════╗
║  Name  ║ Surname ║ address ║ DateCreated ║
╠════════╬═════════╬═════════╬═════════════╣
║ John   ║ Keller  ║ 106 end ║ 2016-06-23  ║
║ Mary   ║ Smith   ║ 114 end ║ 2016-06-25  ║
║ prince ║ jordan  ║ NULL    ║ 2016-06-23  ║
╚════════╩═════════╩═════════╩═════════════╝
2
  • Hi M.Ali thanks for the response. This query only retrieves the unique rows, it does not filter them using null count. it should first check the most complete record on the duplicates (the row with less nulls) and return it. If the nulls are equal. It should take the one with the max date (the one with the most recent date)
    – Shazy
    Jun 6, 2016 at 5:56
  • Sorry, i was not doing it right... this works perfectly fine. :)
    – Shazy
    Jun 6, 2016 at 7:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.