27,579
社区成员
发帖
与我相关
我的任务
分享
select *,ltrim((cast([及格人数] as decimal(18,2))*100/(cast([及格人数] as decimal(18,2))+cast([不及格人数] as decimal(18,2)))))+'%' as [及格率]
if object_id('tempdb.dbo.#stu') is not null drop table #stu
go
create table #stu (学生编号 varchar(4),分数 int,科目 varchar(4))
insert into #stu
select 'bob1',32,'语文' union all
select 'bob2',85,'语文' union all
select 'bob2',80,'数学' union all
select 'bob1',65,'数学' union all
select 'bob1',90,'英语' union all
select 'bob3',75,'语文'
select 科目
,sum(case when 分数>=60 then 1 else 0 end) as 及格
,sum(case when 分数<60 then 1 else 0 end) as 不及格
,1.*sum(case when 分数>=60 then 1 else 0 end)/COUNT(学生编号)*100 as 及格率
from #stu group by 科目
------------------------
科目 及格 不及格 及格率
数学 2 0 100.00000000000
英语 1 0 100.00000000000
语文 2 1 66.66666666600
select *,ltrim((cast([及格人数] as int)/(cast([及格人数] as int)+cast([不及格人数] as int))))+'%' as [及格率]
from(
(select [科目],count([分数]) as [及格人数]
from [成绩表]
where [分数] >= 2)a
join
(select [科目],count([分数]) as [不及格人数]
from [成绩表]
where [分数] < 2)b
on a.[科目] = b.[科目]
)U
create table tb (学生编号 varchar(4),分数 int,科目 varchar(4))
insert into tb
select 'bob1',32,'语文' union all
select 'bob2',85,'语文' union all
select 'bob2',80,'数学' union all
select 'bob1',65,'数学' union all
select 'bob1',90,'英语' union all
select 'bob3',75,'语文'
go
--按照60分为及格。
select 科目,
及格 = (select count(1) from tb where 分数 >= 60 and 科目 = t.科目) ,
不及格 = (select count(1) from tb where 分数 < 60 and 科目 = t.科目),
及格率 = cast(100.0*(select count(1) from tb where 分数 >= 60 and 科目 = t.科目)/(select count(1) from tb where 科目 = t.科目) as decimal(18,2))
from tb t
group by t.科目
/*
科目 及格 不及格 及格率
---- ----------- ----------- --------------------
数学 2 0 100.00
英语 1 0 100.00
语文 2 1 66.67
(所影响的行数为 3 行)
*/
--自定义及格分数
declare @score as int
set @score = 60
select 科目,
及格 = (select count(1) from tb where 分数 >= @score and 科目 = t.科目) ,
不及格 = (select count(1) from tb where 分数 < @score and 科目 = t.科目),
及格率 = cast(100.0*(select count(1) from tb where 分数 >= @score and 科目 = t.科目)/(select count(1) from tb where 科目 = t.科目) as decimal(18,2))
from tb t
group by t.科目
/*
科目 及格 不及格 及格率
---- ----------- ----------- --------------------
数学 2 0 100.00
英语 1 0 100.00
语文 2 1 66.67
(所影响的行数为 3 行)
*/
drop table tb
--> 测试数据: #stu
if object_id('tempdb.dbo.#stu') is not null drop table #stu
go
create table #stu (学生编号 varchar(4),分数 int,科目 varchar(4))
insert into #stu
select 'bob1',32,'语文' union all
select 'bob2',85,'语文' union all
select 'bob2',80,'数学' union all
select 'bob1',65,'数学' union all
select 'bob1',90,'英语' union all
select 'bob3',75,'语文'
declare @yw int,@sx int,@yy int
set @yw=50
set @yy=60
set @sx=70
select *,不及格=总人-及格,及格率=ltrim(cast(及格*100.0/总人 as decimal(18,1)))+'%'
from
(
select 科目,
总人=count(*),
及格=sum(case when 分数>=(case 科目 when '语文' then @yw
when '数学' then @sx
when '英语' then @yy end)
then 1 else 0 end)
from #stu
group by 科目
)t
科目 总人 及格 不及格 及格率
---- ----------- ----------- ----------- ------------------------------------------
数学 2 1 1 50.0%
英语 1 1 0 100.0%
语文 3 2 1 66.7%
(3 行受影响)