分类汇总

create table (id int,bj nvarchar(6),zf float) 
insert table values select 1,'1',701 
union 
select 2,'2',702 
union 
select 3,'1',681 
union 
select 4,'2',501 
union 
select 5,'1',401 
union 
select 6,'1',101 

分数段  计1 累1 计2 累2 总计 总累
700    1  1
690    0  1
680    1  2
.      .  .
.      .  .
300    0 
其余    1
举例说明:
红色1表示1班在680 <=zf <690范围有1名学生
绿色2表示1班在680 <=zf范围有2名学生
“计”只是本段人数,“累”是由本段向上,不封顶,“其余”段0 <zf <300,总计=计1+计2+..计n
有n个班就从计1到计n,“累”也是同理
因为班数不定,希望做成能修改的动态SQL,
if object_id('tb') is not null
drop table tb
go

create table tb([编号] int,[班级] nvarchar(10),[成绩] float) 
insert tb 
select 1,'高三1班',701 union 
select 2,'高三1班',702 union 
select 3,'高三2班',675 union 
select 4,'高三2班',501 union 
select 5,'高三2班',401 union 
select 6,'高三1班',459 union
select 1,'高三2班',700 union 
select 2,'高三1班',690 union 
select 3,'高三1班',681 union 
select 4,'高三1班',671 union 
select 5,'高三2班',450 union 
select 6,'高三1班',209

IF OBJECT_ID('f_fsd', N'FN') IS NOT NULL
    DROP FUNCTION f_fsd
go

create function f_fsd(@a int) 
returns varchar(4)
as
begin
  declare @s varchar(4)
  if (@a>0) and (@a <300) 
    set @s='其余'
  else
    set @s=convert(varchar(3),((@a/10)*10))
  return @s
end
go

declare @s nvarchar(4000)
set @s=''
;with t as
(
select dbo.f_fsd([成绩]) as [分数段],[班级], count(*) as [人数] 
from tb
group by dbo.f_fsd([成绩]),[班级]
)
select @s=@s+',['+班级+'人数]=sum(case when [班级]='+quotename([班级],'''')+' then [人数] else 0 end),'+
  '['+班级+'人数累计]=isnull((select sum([人数]) from t'+
  ' where (([分数段]>=t1.[分数段] and [分数段]<>''其余'')or(t1.[分数段]=''其余''))'+
  ' and [班级]='+
   quotename([班级],'''')+'),0)'
from t group by [班级]

declare @i int
declare @s2 varchar(1200)
set @s2=''
set @i=700
while @i>290
begin
  set @s2=@s2+' union select '''+convert(char(3),@i)+''',''dump'',0'
  set @i=@i-10
end;
set @s2=@s2+' union select ''其余'',''dump'',0'

exec(
'with t as'+
'('+
'  select dbo.f_fsd([成绩]) as [分数段],[班级], count(*) as [人数]'+
'  from tb'+
'  group by dbo.f_fsd([成绩]),[班级]'+
@s2+
') '+
' select [分数段]'+@s+
' ,[总计]=(select sum([人数]) from t where [分数段]=t1.[分数段])'+
' ,[总累计]='+
' case when [分数段]=''其余'' then (select sum([人数]) from t) else '+
'(select sum([人数]) from t where [分数段]>=t1.[分数段] and [分数段]<>''其余'') end'+
' from t t1 group by [分数段]'+
' order by (case when [分数段]=''其余'' then 1 else 0 end), [分数段] desc')

--drop table tb
--drop function f_fsd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值