with CteData as (
/*0)测试数据,可以来自数据库*/
select 'A01' as FCode, '男' as FGender
union all
select 'A02' as FCode, '男' as FGender
union all
select 'A03' as FCode, '男' as FGender
union all
select 'A04' as FCode, '女' as FGender
union all
select 'A05' as FCode, '女' as FGender
union all
select 'A06' as FCode, '男' as FGender
union all
select 'A07' as FCode, '男' as FGender
union all
select 'A08' as FCode, '女' as FGender
), CteAddNo as (
/*1)数据添加行号*/
select row_number() over ( order by FCode ) as FNo,
x.*
from CteData x
), CteAddGrpNo as (
/*2)继续添加分组序号*/
select 1 as FGrpNo,
x.FNo as FNo,
x.FCode as FCode,
x.FGender as FGender
from CteAddNo x
where x.FNo = 1
union all
select iif(c.FGender = d.FGender, c.FGrpNo, c.FGrpNo + 1) as FGrpNo,
d.FNo as FNo,
d.FCode as FCode,
d.FGender as FGender
from CteAddGrpNo c, CteAddNo d
where d.FNo = c.FNo + 1
), CteGroup as (
/*3)按分组序号分组*/
select min(x.FCode) as FCode1,
max(x.FCode) as FCode2,
min(x.FGender) as FGender
from CteAddGrpNo x
group by x.FGrpNo
)
select *
from CteGroup
sqlserver数据库写的,答案来自其他大佬