Contents

[-]
1 문제1
2 풀이1
3 풀이2


1 문제1 #

테이블에....
col1 . col2
------------
A       a1
A       b1
B       a1
C       b1
D       a1
D       b1
D       c1


이렇게 있을때 조건으로 (a1, b1) 을 던져서 a1 과 b1 둘다 포함하고 있는 
A - a1, A - b1, D-a1, D-b1 만 가져오고 싶습니다. B - a1, C - b1, D - c1 의 로우는 빼고요


실제로는 조건의 (a1, b1)  는 다른 테이블에서 조회한 값입니다.
따로 그룹을 지어야 한다면 어떻게 해야 할지...힌트라도 부탁드립니다.
* 질문 원본: http://www.devpia.com/MAEUL/Contents/Post.aspx?BoardID=41&MAEULNO=17&mode=Reply&no=7099&page=1
* 원하는 결과는 명확하진 않지만, 소스 테이블의 형태라고 생각하고..

2 풀이1 #

--drop table #temp
select 'A' col1, 'a1' col2 into #temp union all
select 'A' col1, 'b1' col2 union all
select 'B' col1, 'a1' col2 union all
select 'C' col1, 'b1' col2 union all
select 'D' col1, 'a1' col2 union all
select 'D' col1, 'b1' col2 union all
select 'D' col1, 'c1' col2 

--머 대충 이렇게..
;with rs
as
(
	select 
		col1
	,	min(case when seq = 1 then col2 end)col2
	,	min(case when seq = 2 then col2 end) col3
	from #temp a
		cross join (select 1 seq union all select 2) b
	where col2 in ('a1', 'b1')
	group by
		col1
)
select a.*
from #temp a
	inner join rs b
		on a.col1 = b.col1
		and a.col2 in (b.col2, b.col3)
where b.col2 is not null
and b.col3 is not null

3 풀이2 #

--머.. 대충 이렇게도 풀 수 있다.. 테이블을 3번이나 읽었다..
select 
	c.*
from #temp a
	inner join #temp b
		on a.col1 = b.col1
	inner join #temp c
		on a.col1 = c.col1
		and c.col2 in (a.col2, b.col2)
where a.col2 = 'a1'
and b.col2 = 'b1'