考虑下面的3列。我需要获得具有相同col1的列,其col2值为1和2,col3具有2个不同的col2值,其中col1与col2和col3相同
Col1 Col2 Col3
A 1 IND
A 2 IND
A 3 IND
B 1 IND
B 2 PAK
B 3 IND
B 4 IND
C 1 IND
C 2 IND
C 3 PAK
C 4 PAK
D 1 IND
D 2 PAK
E 1 PAK
E 2 SA
结果将如下所示
Col1 Col2 Col3
B 1 IND
B 2 PAK
D 1 IND
D 2 PAK
E 1 PAK
E 2 SA
以下是我为col1和col2尝试的内容:
select col1 from your_table
where col2 in (1,2)
group by col1
having count(distinct col2) > 1
答案 0 :(得分:1)
根据您的要求,可以忽略Col2中包含3和4的行
喜欢这个
SELECT
*
FROM
MyTable M1
JOIN
MyTable M2 ON M1.COl1 = M2.COl1
WHERE
M1.Col2 IN (1, 2)
AND
M2.Col2 IN (1, 2)
AND
M2.Col3 <> M1.COl3
答案 1 :(得分:1)
一种方法是聚合。以下内容获取符合您条件的A列值:
select col1
from t
where col2 in (1, 2)
group by col1
having min(col3) <> max(col3);
如果要获取原始行,有多种方法。除了明显的(例如in
,exists
和join
)之外,您还可以使用窗口函数:
select col1, col2, col3
from (select t.*,
min(col3) over (partition by col1) as mincol3,
max(col3) over (partition by col1) as maxcol3
from t
where col2 in (1, 2)
) t
where mincol3 <> maxcol3;