简体   繁体   中英

SQL Server : two columns with the same row values in the same table

I have a huge dataset with about 400,000 rows. I want to select only the rows where the value of the second column ( val ) exists in the third column ( ecr ) in the same table.

For example, in the sample screenshot shown below, the value of the column val on the second row ( 4294939057 ) is equal to third row value of column ecr .

I tried with the following query but it doesn't seem to give the correct rows.

Any tips would be very much appreciated.

use dbTest

select val, ecr 
from tableTest 
group by val 
having COUNT (val) > 1

I am using SQL Server 2008.

在此处输入图片说明

You should use a self join (could be you need proper separated index on val and ecr due the dimension of your table )

select a.*, b.* 
from tableTest as a 
  inner join tableTest as b  
    on a.val  = b.ecr 

If you do not want the full output from an inner join, you could use something like this:

select *
from tableTest as t
where exists (
  select 1 
  from tableTest as i  
  where t.val  = i.ecr
  )

The other option besides the join is a subquery:

SELECT *
FROM tableTest
WHERE val IN (SELECT ecr FROM tableTest)

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