34,590
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据: @table
declare @table table (歌名 varchar(2),歌手名字 varchar(1),歌手性别 varchar(2))
insert into @table
select 'aa','a','男' union all
select 'bb','a','男' union all
select 'cc','b','男' union all
select 'dd','b','男' union all
select 'ii','e','男' union all
select 'jj','e','女' union all
select 'kk','e','女' union all
select 'll','f','女' union all
select 'mm','f','女' union all
select 'nn','g','女' union all
select 'ee','c','男' union all
select 'ff','c','男' union all
select 'gg','d','男' union all
select 'hh','d','男' union all
select 'oo','g','女' union all
select 'pp','h','女' union all
select 'qq','i','女' union all
select 'rr','i','女'
SELECT 歌名,歌手名字,歌手性别
FROM (
SELECT *,r1=ROW_NUMBER()OVER(PARTITION BY 歌手性别 order by getdate()),
r2=ROW_NUMBER()OVER(order by 歌手性别)
FROM @table
) t
ORDER BY r1,r2
/*
歌名 歌手名字 歌手性别
---- ---- ----
aa a 男
oo g 女
bb a 男
pp h 女
cc b 男
qq i 女
dd b 男
rr i 女
ii e 男
jj e 女
ee c 男
kk e 女
ff c 男
ll f 女
gg d 男
mm f 女
hh d 男
nn g 女
(18 行受影响)
*/
借叶子测试数据
--> 测试数据: @table
declare @table table (歌名 varchar(2),歌手名字 varchar(1),歌手性别 varchar(2))
insert into @table
select 'aa','a','男' union all
select 'bb','a','男' union all
select 'cc','b','男' union all
select 'dd','b','男' union all
select 'ee','c','男' union all
select 'ff','c','男' union all
select 'gg','d','男' union all
select 'hh','d','男' union all
select 'ii','e','男' union all
select 'jj','e','女' union all
select 'kk','e','女' union all
select 'll','f','女' union all
select 'mm','f','女' union all
select 'nn','g','女' union all
select 'oo','g','女' union all
select 'pp','h','女' union all
select 'qq','i','女' union all
select 'rr','i','女'
;with maco as
(
select 2*(row_number() over (order by 歌名))-1 as rid,歌名
,歌手名字,歌手性别 from @table where 歌手性别='男'
),maco1 as
(
select 2*(row_number() over (order by 歌名)) as rid,歌名
,歌手名字,歌手性别 from @table where 歌手性别='女'
)
select * from maco union all
select * from maco1 order by rid
/*
(18 row(s) affected)
rid 歌名 歌手名字 歌手性别
-------------------- ---- ---- ----
1 aa a 男
2 jj e 女
3 bb a 男
4 kk e 女
5 cc b 男
6 ll f 女
7 dd b 男
8 mm f 女
9 ee c 男
10 nn g 女
11 ff c 男
12 oo g 女
13 gg d 男
14 pp h 女
15 hh d 男
16 qq i 女
17 ii e 男
18 rr i 女
(18 row(s) affected)
*/
select * from
(select row_number()over(partition by 性别 order by getdate()) no,* from tb )a
order by no,性别