日期:2014-05-18  浏览次数:20484 次

请看一下,这个查询统计语句错在哪里
select   count(*)   成绩大于80的条数   from
(
    select   t1.姓名,   t1.考试名称ID,   t2.tname   as   考试名称,   t1.试卷名称,   sum(t1.分数)   成绩
    from   t1,   t2
    where   t1.考试名称ID   =   t2.id
    group   by   t1.考试名称ID,   t2.tname,   t1.姓名,   t1.试卷名称
)   t
where   成绩   >   80


这样写是正确的,


select   t.*,count(*)   成绩大于80的条数   from
(
    select   t1.姓名,   t1.考试名称ID,   t2.tname   as   考试名称,   t1.试卷名称,   sum(t1.分数)   成绩
    from   t1,   t2
    where   t1.考试名称ID   =   t2.id
    group   by   t1.考试名称ID,   t2.tname,   t1.姓名,   t1.试卷名称
)   t
where   成绩   >   80


可是这样写是错的,应该如何改?

------解决方案--------------------
--上午那个?


create table t1(姓名 varchar(10),考试名称ID int,试卷名称 varchar(10),题型 varchar(10),分数 decimal(5, 2))
insert t1 select 'aaa ', 1, '语文 ', '选择题 ', 20
union all select 'aaa ', 1, '语文 ', '填空题 ', 30
union all select 'aaa ', 1, '语文 ', '单选题 ', 40
union all select 'bbb ', 1, '数学 ', '选择题 ', 10
union all select 'bbb ', 1, '数学 ', '填空题 ', 30
union all select 'bbb ', 1, '数学 ', '单选题 ', 20
union all select 'ccc ', 2, '语文 ', '选择题 ', 20
union all select 'ccc ', 2, '语文 ', '填空题 ', 30
union all select 'ccc ', 2, '语文 ', '单选题 ', 30
union all select 'ddd ', 2, '数学 ', '选择题 ', 10
union all select 'ddd ', 2, '数学 ', '填空题 ', 30
union all select 'ddd ', 2, '数学 ', '单选题 ', 20

create table t2(id int,tname varchar(10))
insert t2 select 1, '期中 '
union all select 2, '期末 '

select 姓名,考试名称ID,试卷名称,sum(分数) 分数 from t1 group by 姓名,考试名称ID,试卷名称 having sum(分数) > 80

drop table t1, t2

/*
姓名 考试名称ID 试卷名称 分数
---------- ----------- ---------- ----
aaa 1 语文 90.00
(所影响的行数为 1 行)
*/


------解决方案--------------------
select t.* ,(select count(*) 成绩大于80的条数 from
( select t1.姓名, t1.考试名称ID, t2.tname as 考试名称, t1.试卷名称, sum(t1.分数) 成绩 from t1, t2 where t1.考试名称ID = t2.id group by t1.考试名称ID, t2.tname, t1.姓名, t1.试卷名称) t where 成绩 > 80)
from ( select t1.姓名, t1.考试名称ID, t2.tname as 考试名称, t1.试卷名称, sum(t1.分数) 成绩 from t1, t2 where t1.考试名称ID = t2.id group by t1.考试名称ID, t2.tname, t1.姓名, t1.试卷名称) t where 成绩 > 80