简体   繁体   English

SQL Server:同一表中具有相同行值的两列

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

I have a huge dataset with about 400,000 rows. 我有一个庞大的数据集,大约有40万行。 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. 我只想选择同一表的第三列( ecr )中第二列( val )的值所在的行。

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 . 例如,在下面所示的样本屏幕截图,该列的值val在第二行(4294939057)等于列的第三行值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. 我正在使用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 ) 您应该使用自我联接(由于表的尺寸,您可能需要在val和ecr上使用适当的分隔索引)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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