create table T(A int, B int, C varchar(10))
insert T select 1, 2, 'H'
union all select 1, 2, 'J'
union all select 1, 2, 'K'
select A, B,
C1=(select min(C) from T where A=tmp.A and B=tmp.B),
C2=(select top 1 C from T where A=tmp.A and B=tmp.B and C not in(
select min(C) from T where A=tmp.A and B=tmp.B union all select max(C) from T where A=tmp.A and B=tmp.B
)),
C3=(select max(C) from T where A=tmp.A and B=tmp.B)
from T as tmp
group by A, B
--result
A B C1 C2 C3
----------- ----------- ---------- ---------- ----------
1 2 H J K
create table T(A int, B int, C varchar(10))
insert T select 1, 2, 'S1'
union all select 1, 2, 'S3'
union all select 1, 2, 'S2'
insert into t values(2,3,'s1')
insert into t values(2,2,'s2')
declare @table varchar(5000)
set @table = 'select a,b,'
select @table=@table+'(select c from t bb where bb.c='+QUOTENAME(c,'''')+
' and bb.a=aa.a and bb.b=aa.b)'+QUOTENAME(c)+','
from t group by c
set @table = left(@table,len(@table)-1)+'from t aa group by a,b'
exec (@table)