请教个sql问题吧,一张表,有字段: 部门、姓名 显示序号
A部门 张三1 001
A部门 张三2 002
A部门 张三3 003
A部门 张三4 004
B部门 李四1 005
B部门 李四2 006
B部门 李四3 007
B部门 李四4 008
我想显示出部门列表(去除重复)按照显示序号排序,并且统计出该部门下面有多少人,用一条sql如何实现啊?
输出成一个数组。
------解决方案--------------------
select 部门, 人数
from (
select 部门,
count(姓名) over(partition by 部门) 人数,
row_number() over(partition by 部门 order by 数量) 排序,
row_number() over(order by 数量) 排序1
from tabname ) tmp
where 排序 = 1
order by 排序1;
------解决方案--------------------
if object_id('[tb]') is not null drop table [tb]
create table tb (class varchar(10),name varchar(7),id varchar(10))
insert into tb
select 'A部门','张三1','001'union all
select 'A部门','张三2','002'union all
select 'A部门','张三3','003'union all
select 'A部门','张三4','004'union all
select 'B部门','李四1','005'union all
select 'B部门','李四2','006'union all
select 'B部门','李四3','007'union all
select 'B部门','李四4','008'
go
select class,count(class)as count from
(
select *,row_number() over(partition by class order by id asc) as rn from tb
)t group by class
--class count
--A部门 4
--B部门 4