SQL查询问题

buyue__ 2011-05-27 09:13:24
假设有个表,字段分别为:歌名 歌手名字 歌手性别

我要建立的查询是:按歌手性别(男-女-男-女。。。循环),歌手名字(前后不重复,尽量离散)排列
给个思路
...全文
90 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
htl258_Tony 2011-05-27
  • 打赏
  • 举报
回复
--> 测试数据: @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 行受影响)
*/
借叶子测试数据
叶子 2011-05-27
  • 打赏
  • 举报
回复

--> 测试数据: @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)


*/
快溜 2011-05-27
  • 打赏
  • 举报
回复
select * from 
(select row_number()over(partition by 性别 order by getdate()) no,* from tb )a
order by no,性别

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧