Try the following 2 queryselect *from( select gr, tonameid, min(fromnameid) as fromnameid from #temp group by gr, tonameid) awhere tonameid = (select top 1 tonameid from #temp x where x.gr = a.gr)order by gr, tonameid, fromnameidselect *from ( select gr, tonameid, 0 as fromnameid from #temp group by gr, tonameid union all select gr, 0, fromnameid from #temp group by gr, fromnameid) uorder by gr, tonameid, fromnameid
KH