62,052
社区成员
发帖
与我相关
我的任务
分享
create table #QQ
(
姓名 varchar(20),
数量合计 int,
部门编号 int
)
insert into #QQ select '刘虹',54,4
union all select '徐文涛',45,4
union all select '张少更',39,7
union all select '徐震',28,5
union all select '宋斌',24,4
union all select '王善明',23,7
select 姓名,数量合计,(select count(*)+1 from #QQ where 数量合计>Q.数量合计) 名次
from #QQ Q
姓名 数量合计 名次
-------------------- ----------- -----------
刘虹 54 1
徐文涛 45 2
张少更 39 3
徐震 28 4
宋斌 24 5
王善明 23 6
(6 行受影响)
--2000要用临时表
IF OBJECT_ID('A') IS NOT NULL
DROP TABLE A
go
create table a(姓名 varchar(20),数量合计 int, 部门编号 int)
insert into a select '刘虹', 54, 4
union all select '徐文涛', 45, 4
union all select '张少更', 39, 7
union all select '徐震', 28, 5
union all select '宋斌', 24 ,4
union all select '王善明', 23, 7
union all select '王善明', 33, 7 --为了数量合计的效果更明显
go
if object_id('tempdb..#tb') is not null
drop table #tb
go
select 姓名, sum(数量合计) as 数量合计,部门编号,名次=identity(int, 1,1) into #tb
from a
group by 姓名,部门编号
order by 数量合计 desc
select * from #tb
/*
姓名 数量合计 部门编号 名次
-------------------- ----------- ----------- -----------
王善明 56 7 1
刘虹 54 4 2
徐文涛 45 4 3
张少更 39 7 4
徐震 28 5 5
宋斌 24 4 6
(6 行受影响)
*/
select *,row_number() over(order by cnt) rank from
(
select 姓名,sum(数量) cnt from 表
) T order by rank