如何对查询结果进行分组加序号

Alden 2003-12-17 04:54:36
我想从员工信息表里查询不同部门的人员,并按部门加个序号,显示的结果如下:
-------------------
部门甲 1 John
部门甲 2 Mike
部门甲 3 Tom
部门乙 1 Bill
部门乙 2 Rose
-------------------
不知道如何实现,请各位朋友帮助啊
...全文
84 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
1ssp 2003-12-17
  • 打赏
  • 举报
回复
select dept ,Number=(select count(*)+1 from t1 b where b.name<a.name and a.dept<=b.dept)
,name from t1 a order by dept,name
Alden 2003-12-17
  • 打赏
  • 举报
回复
谢谢各位朋友的大力支持
zjcxc 2003-12-17
  • 打赏
  • 举报
回复
--否则的话,就要用临时表
select 部门,序号=0,姓名 into #t from 表 order by 部门,姓名
declare @部门 varchar(10),@i int
update #t set @i=case @部门 when 部门 then @i+1 else 1 end
,序号=@i,@部门=部门

select * from #t
zjcxc 2003-12-17
  • 打赏
  • 举报
回复
--如果同一个部门,不存在同名的现象,可以用:

select 部门,序号=(select sum(1) from 表 where 部门=a.部门 and 姓名<=a.姓名),姓名
from 表 a
order by 部门,姓名
yujohny 2003-12-17
  • 打赏
  • 举报
回复
select 部门,(select count(*) from 表 where 部门 = t.部门 and 工号<=t.工号) 序号, 姓名 from 表 t order by 部门,序号
gmlxf 2003-12-17
  • 打赏
  • 举报
回复
如果你的名字存在着相同的,那就不行了,那样需要唯一字段。
如victorycyz(中海,学SQL Server的菜鸟)说的。
或者有其他的唯一字段也可以。
select part,
(select count(*) from #t where part=a.part and id<=a.id) num,
name
from #t a order by part
gmlxf 2003-12-17
  • 打赏
  • 举报
回复
-- test:
create table #t(part varchar(10),name varchar(10))
insert #t
select '部门甲','John'
union select '部门甲','Mike'
union select '部门甲','Tom'
union select '部门乙','Bill'
union select '部门乙','Rose'
select * from #t

select part,
(select count(*) from #t where part=a.part and name<=a.name) num,
name
from #t a order by part,name

drop table #t

--result:
(所影响的行数为 5 行)

part name
---------- ----------
部门甲 John
部门甲 Mike
部门甲 Tom
部门乙 Bill
部门乙 Rose

(所影响的行数为 5 行)

part num name
---------- ----------- ----------
部门甲 1 John
部门甲 2 Mike
部门甲 3 Tom
部门乙 1 Bill
部门乙 2 Rose

(所影响的行数为 5 行)

victorycyz 2003-12-17
  • 打赏
  • 举报
回复
select * , identity(int,1,1) as pid into #t from tablename

select a.*, id=(select sum(1) from #t a where 部门=b.部门 and pid<=b.pid)
from #t b

drop table #t

22,209

社区成员

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

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