重复次数排序的问题

ysycysyc 2014-05-04 07:28:44
表MB有三个字段A、B、C,数据如下
A B C
--------------------------------------------
0 4 8
1 4 8
1 4 8
2 4 8
2 4 8
2 5 8
3 5 8
3 5 8
3 5 9
3 5 9
3 5 9
3 9 9
3 9 9
3 9 9
想分别求三列中,0-9的重复次数及得复次数的排序,和整个表中0-9的重复次数及得复次数的排序,上面数据中,A列的结果为

值 重复次数 重复次数排序
------------------------------------------
0 1 4
1 2 3
2 3 2
3 8 1
4 5
5 5
6 5
7 5
8 5
9 5

B列的结果为
值 重复次数 重复次数排序
------------------------------------------
0 4
1 4
2 4
3 4
4 5 2
5 6 1
6 4
7 4
8 4
9 3 3
C列的结果为
值 重复次数 重复次数排序
------------------------------------------
0 3
1 3
2 3
3 3
4 3
5 3
6 3
7 3
8 8 1
9 6 2

综合整个表的排序为
值 重复次数 重复次数排序
------------------------------------------
0 1 8
1 2 7
2 3 6
3 8 2
4 5 5
5 6 4
6 9
7 9
8 8 2
9 9 1

请大家指点
...全文
83 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ysycysyc 2014-05-04
  • 打赏
  • 举报
回复
好用,谢谢!!!
  • 打赏
  • 举报
回复
改一下 select number,cnt,ID=RANK() over(order by cnt desc) from wang3 order by number
  • 打赏
  • 举报
回复
--> 测试数据: [ta]
if object_id('[ta]') is not null 
drop table [ta]
go
create table [ta] ([A] int,[B] int,[C] int)
insert into [ta]
select 0,4,8 union all
select 1,4,8 union all
select 1,4,8 union all
select 2,4,8 union all
select 2,4,8 union all
select 2,5,8 union all
select 3,5,8 union all
select 3,5,8 union all
select 3,5,9 union all
select 3,5,9 union all
select 3,5,9 union all
select 3,9,9 union all
select 3,9,9 union all
select 3,9,9

;with
wang as (select number from master..spt_values where type='p' and number<10),
wang1 as(select a from ta union all select B from ta union all select c from ta),
wang2 as (select A,cnt=COUNT(*) from wang1 group by A),
wang3 as (select number,cnt from wang left join wang2 on wang.number=wang2.A)

select number,cnt,ID=case when cnt is not null then ROW_NUMBER() over ( order by cnt desc) 
						  else (select COUNT(*) from wang3 where cnt is not null)+1 end
from wang3
order by number


0	1	8
1	2	7
2	3	6
3	8	2
4	5	5
5	6	4
6	NULL	9
7	NULL	9
8	8	3
9	9	1

22,199

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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