2012-10-17 64 views
5

说我有输入这样的:在第二列检索基于通用数据第1列行

1st column ---------2nd column 
23 ---------------------- 0080 
23 ---------------------- 0010 
23 ---------------------- 0080 
25 ---------------------- 0010 
25 ---------------------- 0010 
34 ---------------------- 0080 
27 ---------------------- 0010 
27 ---------------------- 0080 

我想要检索具有第2列两个0080和0010的数据第一列的所有行。 结果会是这样的:

1st column--------- 2nd column 
23 ---------------------- 0080 
23 ---------------------- 0010 
23 ---------------------- 0080 
27 ---------------------- 0010 
27 ---------------------- 0080 

从结果可以看出,第一列不包括25至25只0010第2列,以及同为34只0080第2列。

我试过使用嵌套查询,但它变得非常缓慢,因为我的表非常大(包含大约30,000多行)。我正在寻找更快速的大数据表的智能技术。

+0

选择不同的第1列和检查与地方似乎是唯一合理的解决方案,我第二。 – jt234

回答

4
select * from your_table 
where col1 in 
(
    select col1 
    from your_table 
    where col2 in ('0080', '0010') 
    group by col1 
    having count(distinct col2) = 2 
) 
+1

这只会返回每col1值一行,并非全部按要求 –

+1

你是对的。更正它。 –

0
select first 
from t 
where second in ('0080', '0010') 
group by first 
having count(distinct second) = 2 
+0

这也会返回每个col1值只有一行,并非全部按需要。 –

0
SELECT t.Col1,t.Col2 
    FROM dbo.YourTable t 
    JOIN(
    SELECT Col1, 
     MAX(CASE WHEN Col2 = '0010' THEN 1 ELSE 0 END) Has0010, 
     MAX(CASE WHEN Col2 = '0080' THEN 1 ELSE 0 END) Has0080 
     FROM dbo.YourTable 
     GROUP BY Col1 
)FilterTbl f 
    ON t.Col1 = f.Col1 AND f.Has0010 = 1 AND f.Has0080 = 1 
相关问题