简体   繁体   中英

select distinct rows based on column values

In one table i have four columns 'FirstName' , 'LastName' , 'Dob', 'Number' There are multiple rows for the unique 'first Name' and 'LastName' and they can have same or different 'Number' and 'Dob' values

FirstName  LastName   Dob         Number
Alice      Smith      02/03/77    0876543    (require)
Alice      Smith      Null        0876543    (Not require)
Alice      Smith      Null        Null       (Not require)
John       Adam       11/28/63    3265783    (require)
John       Adam       11/28/63    Null       (Not Require)
John       Adam       05/15/58    Null       (require)
Sally      Smith      Null        Null       (require)

I want distinct rows, but I need only one record if either the 'Number'or the 'Dob' matches with other records of same FirstName' and 'LastName' I am lookin for the rows that are labeled 'require' in the example above. The combinations i tried didn't get results i thought they would. Thanks

I would first select all rows that have all four fields populated:

SELECT DISTINCT FirstName, LastName, Dob, Number
FROM customers
WHERE Dob IS NOT NULL And Number IS NOT NULL

Then I would add to the selection the records with NOT NULL values that do not exist in the first selection:

with RequiredSet as (
SELECT DISTINCT FirstName, LastName, Dob, Number
FROM customers
WHERE Dob IS NOT NULL And Number IS NOT NULL
), AdditionalSet as (
SELECT distinct c.FirstName, c.LastName, c.Dob, c.Number
FROM customers c
WHERE Dob IS NOT NULL And NOT EXISTS(SELECT 1 
   FROM RequiredSet r 
   WHERE r.FirstName = c.FirstName And r.LastName=c.LastName And r.Dob=c.Dob)
OR Number IS NOT NULL And NOT EXISTS(SELECT 1 
   FROM RequiredSet r 
   WHERE r.FirstName = c.FirstName And r.LastName=c.LastName And r.Number=c.Number)
)
SELECT FirstName, LastName, Dob, Number
FROM RequiredSet
UNION ALL 
SELECT FirstName, LastName, Dob, Number
FROM AdditionalSet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM