简体   繁体   中英

Selecting two rows in a table which have the same data for a particular column

There is a column in a table(contracts) called service location. I have to show all the rows where the service locations matches any other row in the table.

    Table Example

 A    B    C
 1    2    3
 3    2    1
 2    5    3

I require a query where the first and second rows will be returned based on a comparison on the second column. I am assuming I will need to use a HAVING COUNT( B ) > 1

I came up with this

SELECT  `contract_number` 
FROM  `contracts` 
WHERE  `import_id` =  'fe508764-54a9-41f7-b36e-50ebfd95971b'
GROUP BY  `service_location_id` 
HAVING COUNT(`service_location_id` ) >1  

But it doesn't generate what I exactly need.

Having would do it, but you would need to use it like this

SELECT  *
FROM    Contracts
        INNER JOIN
        (   SELECT  B
            FROM    Contracts
            GROUP BY B
            HAVING COUNT(*) > 1 -- MORE THAN ONE ROW WITH THE SAME VALUE
        ) dupe
            ON dupe.B = Contracts.B

Depending in your indexing you may find a self join performs better though:

SELECT  DISTINCT t1.*
FROM    contracts t1
        INNER JOIN contract` t2
            ON t1.B = t2.B
            AND t1.A <> t2.A

SELECT * FROM sheet1 WHERE C IN (

SELECT C FROM sheet1 GROUP BY C HAVING COUNT( C ) >1 ) ORDER BY C LIMIT 0 , 5000

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