姓名 报名号 身份证 班级 状态
陈磊 105113100001 513901199504174813 01 2
陈俊羊 105113100002 510623199503016118 02 2
陈林 105113100003 511081199402034132 01 2
高卓兴 105113100004 510104199410032112 01 0
胡忠 105113100005 513822199409150019 02 0
黄思豪 105113100006 510104199502121673 01 0
黄添翼 105113100007 513822199410234818 02 0
这样的数据,我需要按照班级统计各个状态的人数,结果如下:
班级 状态2 人数 状态2 人数
01 2 2 0 2
02 2 1 0 2
谢谢了!
陈磊 105113100001 513901199504174813 01 2
陈俊羊 105113100002 510623199503016118 02 2
陈林 105113100003 511081199402034132 01 2
高卓兴 105113100004 510104199410032112 01 0
胡忠 105113100005 513822199409150019 02 0
黄思豪 105113100006 510104199502121673 01 0
黄添翼 105113100007 513822199410234818 02 0
这样的数据,我需要按照班级统计各个状态的人数,结果如下:
班级 状态2 人数 状态2 人数
01 2 2 0 2
02 2 1 0 2
谢谢了!
select 班级,2 as 状态2,
sum(case when 状态 = 2 then 1 else 0 end) as 人数2,
0 as 状态0,
sum(case when 状态 = 0 then 1 else 0 end) as 人数0
from tb
group by 班级,状态2,状态0--状态多了楼主看动态行转列
select 班级,2,count(case when 状态=2 then 1 end) 人数,0,count(case when 状态=0 then 1 end) 人数 from table group by 班级
create table #tb
(姓名 nvarchar(20),报名号 nvarchar(20), 身份证 nvarchar(50), 班级 nvarchar(10), 状态 nvarchar(5))
insert #tb
select '陈磊', '105113100001', '513901199504174813', '01', '2' union all
select '陈俊羊', '105113100002', '510623199503016118', '02', '2' union all
select '陈林', '105113100003', '511081199402034132', '01', '2' union all
select '高卓兴', '105113100004', '510104199410032112', '01', '0' union all
select '胡忠', '105113100005', '513822199409150019', '02', '0' union all
select '黄思豪', '105113100006', '510104199502121673', '01', '0' union all
select '黄添翼', '105113100007', '513822199410234818', '02', '0'declare @sql as nvarchar(4000)
set @sql=''
select @sql=@sql+',min(状态) as ''状态'+状态+''',sum(case 状态 when '''+状态+''' then 1 else 0 end) as 人数'
from (select distinct 状态 from #tb) as t
set @sql='select 班级'+@sql+' from #tb group by 班级'
exec(@sql)