如何选择包含提供值的列的行

时间:2015-10-01 19:28:01

标签: sql sql-server tsql sql-server-2012

大家都考虑跟随我的表结构

Col1   Col2 Col3 
A       1    Aa
A       2    Bb
A       1    Aa
A       4    Bb
B       2    Bb
C       1    Aa
C       5    Bb
D       3    Aa

如您所见,Col3包含Aa和Bb的distint值。

我正在尝试编写一个查询,该查询仅返回Col1具有值Aa和Bb(两者)或Aa(单独)的行。

要点是删除那些只有Bb与不同的Col1值相关联的行。

示例 - 对于Col1,A的不同值应在相应的Col3中具有Aa和Bb / Aa。 Col1中B的值违反了此要求,因此结果集不应包含与B关联的行。

预期产出 -

Col1   Col2 Col3 
A       1    Aa
A       2    Bb
A       1    Aa
A       4    Bb
C       1    Aa
C       5    Bb
D       3    Aa

5 个答案:

答案 0 :(得分:7)

SELECT * 
FROM TableName T 
WHERE EXISTS ( SELECT 1 
               FROM TableName
               WHERE T.Col1 = Col1 
                AND  Col3 = 'Aa')

答案 1 :(得分:2)

另一种方法是使用intersectunion

Fiddle with sample data

select * from t where col1 in (
select col1 from t where col3 = 'Aa'
intersect
select col1 from t where col3 = 'Bb'
union 
select col1 from t where col3 = 'Aa')

答案 2 :(得分:0)

这是另一个选项,使用您的值而不是表格。:

Select
T.*
From
(Select
    'A' As Col1, 1 As Col2, 'Aa' As Col3
Union All
Select
    'A', 2, 'Bb'
Union All
Select
    'A',1,'Aa'
Union All
Select
'A',4,'Bb'
Union All
Select
'B',2,'Bb'
Union All
Select
'C',1,'Aa'
Union All
Select
'C',5,'Bb'
Union All
Select
'D',3,'Aa'
) T
Inner Join
(Select
    Col1
    ,Sum(Case When Col3 = 'Aa' Then 1 Else 0 End) As CountAa
From
    (Select
        'A' As Col1, 1 As Col2, 'Aa' As Col3
    Union All
    Select
        'A', 2, 'Bb'
    Union All
    Select
        'A',1,'Aa'
    Union All
    Select
    'A',4,'Bb'
    Union All
    Select
    'B',2,'Bb'
    Union All
    Select
    'C',1,'Aa'
    Union All
    Select
    'C',5,'Bb'
    Union All
    Select
    'D',3,'Aa'
    ) T2
Group By
    Col1
) T3 On T.Col1 = T3.Col1
Where
T3.CountAa > 0

用表格简化,那是:

Select
T.*
From
YourTable T
Inner Join
(Select
    Col1
    ,Sum(Case When Col3 = 'Aa' Then 1 Else 0 End) As CountAa
From
    YourTable T2
Group By
    Col1
) T3 On T.Col1 = T3.Col1
Where
T3.CountAa > 0

这个方法的好处是你可以在更复杂的数据集上添加大量条件语句。

答案 3 :(得分:0)

String htmlString = "YOUR HTML HERE"
Pattern pattern = Pattern.compile("PLCMPLD00016.html">(.*?)<\\/a>|"ar">(.*?)<\\/td>");

Matcher matcher = pattern.matcher(htmlString );
while (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

答案 4 :(得分:0)

根据您的实际数据,row_number()可能是另一种可能性:

select Col1, Col2, Col3
from (
  select *, i = row_number() over(partition by Col1 order by Col1, Col3)
  from TableName
) a
where i > 1 or Col3 like 'Aa'