-- 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 #tselect part, (select count(*) from #t where part=a.part and name<=a.name) num, name from #t a order by part,namedrop 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(中海,学SQL Server的菜鸟)说的。 或者有其他的唯一字段也可以。 select part, (select count(*) from #t where part=a.part and id<=a.id) num, name from #t a order by part
select 部门,(select count(*) from 表 where 部门 = t.部门 and 工号<=t.工号) 序号, 姓名 from 表 t order by 部门,序号
--如果同一个部门,不存在同名的现象,可以用:select 部门,序号=(select sum(1) from 表 where 部门=a.部门 and 姓名<=a.姓名),姓名 from 表 a order by 部门,姓名
--否则的话,就要用临时表 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
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
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 #tselect part,
(select count(*) from #t where part=a.part and name<=a.name) num,
name
from #t a order by part,namedrop 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(中海,学SQL Server的菜鸟)说的。
或者有其他的唯一字段也可以。
select part,
(select count(*) from #t where part=a.part and id<=a.id) num,
name
from #t a order by part
from 表 a
order by 部门,姓名
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
,name from t1 a order by dept,name