日期:2014-05-18 浏览次数:20668 次
create table tb(id int, subjectid int, content varchar(10) , isright int) insert into tb values(1 , 101 , '题目内容', 0 ) insert into tb values(2 , 101 , '题目内容', 0 ) insert into tb values(3 , 101 , '题目内容', 1 ) insert into tb values(4 , 101 , '题目内容', 1 ) insert into tb values(5 , 102 , '题目内容', 0 ) insert into tb values(6 , 102 , '题目内容', 1 ) insert into tb values(7 , 103 , '题目内容', 0 ) insert into tb values(8 , 103 , '题目内容', 1 ) insert into tb values(9 , 103 , '题目内容', 1 ) go select subjectid, 错误率 = cast(cast(sum(case isright when 0 then 1 else 0 end ) * 100.0 / (select count(1) from tb where subjectid = t.subjectid) as decimal(18,2)) as varchar) + '%' from tb t group by subjectid drop table tb /* subjectid 错误率 ----------- ------------------------------- 101 50.00% 102 50.00% 103 33.33% (所影响的行数为 3 行) */
------解决方案--------------------
select subjectid,content,count(*) as 题目数量, sum(case when isright=0 then 1 else 0 end) as 错误数量, cast(sum(case when isright=0 then 1 else 0 end)/count(*)*100 as char(2))+'%' as 错误率 from tb group by subjectid,content order by sum(case when isright=0 then 1 else 0 end) desc
------解决方案--------------------
declare @t table(id int,subjectid int,[content] varchar(10), isright bit) insert @t select 1,101,'题目内容',0 insert @t select 2,101,'题目内容',0 insert @t select 3,101,'题目内容',1 insert @t select 4,101,'题目内容',1 insert @t select 5,102,'题目内容',0 insert @t select 6,102,'题目内容',1 insert @t select 7,103,'题目内容',0 insert @t select 8,103,'题目内容',1 insert @t select 9,103,'题目内容',1 select subjectid,[content],count(1) 题目出现总数,sum(1-isright) 每题出错个数 from @t group by subjectid,content order by subjectid subjectid content 题目出现总数 每题出错个数 ----------- ---------- ----------- ----------- 101 题目内容 4 2 102 题目内容 2 1 103 题目内容 3 1 (3 行受影响)
------解决方案--------------------
create table tb(id int, subjectid int, content varchar(10) , isright int) insert into tb values(1 , 101 , '题目内容', 0 ) insert into tb values(2 , 101 , '题目内容', 0 ) insert into tb values(3 , 101 , '题目内容', 1 ) insert into tb values(4 , 101 , '题目内容', 1 ) insert into tb values(5 , 102 , '题目内容', 0 ) insert into tb values(6 , 102 , '题目内容', 1 ) insert into tb values(7 , 103 , '题目内容', 0 ) insert into tb values(8 , 103 , '题目内容', 1 ) insert into tb values(9 , 103 , '题目内容', 1 ) go select subjectid, sum(case isright when 0 then 1 else 0 end)'错误数]', count(1) '总题目数', cast(sum(case isright when 0 then 1 else 0 end ) * 100.0 / (select count(1) from tb where subjectid = t.subjectid) as decimal(18,2)) '错误率' from tb