简体   繁体   中英

Selecting rows that match based on another rows value

Looking for a little bit of help with an SQL query please. I have a table similar to the below:

id  |   uprn           |   driverlicence      |
===============================================
1   |   100000000420   |   FARME100165AB5EW   |
2   |   100000011420   |   FARME100165AB5EW   |
3   |   100000022420   |   GARME100165AB5EW   |
4   |   100000033420   |   HARME100165AB5EW   |

Essentially what I want to do is get all the rows where the uprn is different, but the driverlicence is the same. So in the example above, I would only get the first 2 rows back as the driverlicence will match, but the uprn does not.

I don't have an existing query I can share as I'm not sure how to go about this and I've not been about to find anything useful from search the web.

My SQL knowledge is a bit rusty, but this should do:

SELECT a.id, a.uprn, a.driverlicence
FROM mytable a
JOIN mytable b BY a.driverlicence == b.driverlicence
WHERE a.uprn != b.uprn

or alternatively

SELECT *
FROM mytable
WHERE EXISTS(
    SELECT * 
    FROM mytable other 
    WHERE uprn != other.uprn AND driverlicence == other.driverlicence)

I think this is an XY problem.You can try this sql.if you have other needs.please comment to me.

select uprn,driverlicence from t1 where driverlicence in 
(
    -- select duplicate driverlicence
    select driverlicence from t1 where uprn in 
        -- remove duplicate uprn
        (select uprn from t1 group by uprn having count(*)<2)
    group by driverlicence having count(*)>1
)
     uprn     |  driverlicence
--------------+------------------
 100000000420 | FARME100165AB5EW
 100000011420 | FARME100165AB5EW

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