求一个在一张表里面按不同条件合计的在一行的语句
表达能力不是很好,请见谅:
一个这样的表,有id(编号),name(姓名),subject(科目),testtype(考试类型),score(分数)这几个字段;
科目有语文,数学,英语;
考试类型是指期中考试和期末考试;
我需要sql查询到这样的结果:id,name,total(总分),midtermtotal(期中总分),endtermtotal(期末总分),midtermchn(语文总分)。
建表语句:
create table student_score
(id int,name varchar (10),subject varchar (10),testtype varchar (10),score decimal(5,1));
insert into student_score
select 1,'王一','语文','期中',75.1 union all
select 2,'王一','语文','期末',87.1 union all
select 3,'王一','英语','期中',73.4 union all
select 4,'李二','数学','期中',67.6 union all
select 5,'李二','英语','期中',90.4 union all
select 6,'李二','语文','期中',59.7 union all
select 7,'张三','英语','期中',60.0 union all
select 8,'张三','语文','期末',78.3 union all
select 9,'周四','英语','期中',67.0 union all
select 10,'周四','语文','期中',84.5 union all
select 11,'周四','语文','期末',83.0 union all
select 12,'刘五','英语','期中',74.8 union all
select 13,'刘五','语文','期中',87.5 union all
select 14,'刘五','数学','期末',76.5 union all
select 15,'刘五','语文','期末',72.1 union all;
万分感谢您看我的帖子! select SQL 条件
[解决办法]
SELECT id,NAME, SUM(Score) 总分,
其中总分=sum(case when testtype='期中' then score else 0 end),
其末总分=sum(case when testtype='期末' then score else 0 end ) ,
语文总分=sum(case when subject='语文' then score else 0 end )
FROM student_score
GROUP BY Id,Name
with cte
as
(
select
t.name
,max(case t.testtype when '期中' then t.score else 0 end) 期中
,max(case t.testtype when '期末' then t.score else 0 end) 期末
from
student_score t
group by t.name
)
select cte.*,cte.期中+cte.期末 总分
from
cte
SELECT NAME, SUM(Score) 总分,
其中总分=sum(case when testtype='期中' then score else 0 end),
其末总分=sum(case when testtype='期末' then score else 0 end ) ,
语文总分=sum(case when subject='语文' then score else 0 end ),
[80科目以上个数]=sum(CASE WHEN score>80 then 1 else 0 end )
FROM student_score
GROUP BY NAME
id,就不分组了,否则没意义