我有一个数据表,结构为 BMDM,XM,XBM,即   部门代码,姓名,性别代码 我里面的数据是这样的: 
1.每个部门的人数不一定相等 
2.所有数据男女数不一定相等 
要求查询结果: 
1.尽量男女搭配,男或女多了的,则同一性别排在一起; 
2.尽量将同一部门的分开,比如A部门尽量不要同A部门排列在一起; 
3.相同情况下,第1条优先 输出格式为: 
某某(男)\某某(女) 
create table tb(BMDM int, XM varchar(16), XBM int)insert tb select 1, 'A男', 1
union all select 1, 'B男', 1
union all select 1, 'C女', 0
union all select 1, 'D女', 0
union all select 1, 'E女', 0
union all select 2, 'F男', 1
union all select 2, 'G男', 1
union all select 2, 'H男', 1
union all select 2, 'I女', 0
union all select 2, 'J女', 0select nId=identity(int,1,1), XM into #M from
(
    select top 50 percent XM from tb order by XBM desc, BMDM desc
) tbselect nId=identity(int,1,1), XM into #F from
(
    select top 50 percent XM from tb order by XBM, BMDM
) tbselect nId=coalesce(m.nId, f.nId), 配对=m.XM+'(男)\'+f.XM+'(女)'
from #M m full join #F f on m.nId=f.nId