--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