7、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )
①、
select
S.sid,
S.sname,
coalesce(cast(countcid AS varchar(4) ), '0' ) AS "选课总数",
coalesce(cast(sumscore AS varchar(4)), 'null' ) AS "总成绩"
FROM student AS S left join(
select sid,
count(cid) AS countcid,
sum(score) AS sumscore
from SC
group by sid) AS SC1
ON S.sid=SC1.sid;
sid | sname | 选课总数 | 总成绩
------------+------------------------+----------+--------
07 | 郑竹 | 2 | 187
02 | 钱电 | 3 | 210
06 | 吴兰 | 2 | 65
03 | 孙风 | 3 | 240
04 | 李云 | 3 | 100
05 | 周梅 | 2 | 163
01 | 赵雷 | 3 | 189
10 | 李四 | 0 | null
11 | 李四 | 0 | null
12 | 赵六 | 0 | null
13 | 孙七 | 0 | null
09 | 张三 | 0 | null
(12 行记录)
②、网络答案:
SELECT S2.sid, S2.sname, COUNT(S1.Sid) AS 选课总数,
COALESCE(CAST(SUM(score) AS VARCHAR(4)), 'NULL') AS 总成绩
FROM SC AS S1 RIGHT OUTER JOIN Student AS S2
ON S1.Sid = S2.Sid
GROUP BY S2.sid, S2.sname;
被搞蒙了……选课总数不用COALESCE 函数吗?(不用呗,因为count()结果会是0)
sid | sname | 选课总数 | 总成绩
------------+------------------------+----------+--------
03 | 孙风 | 3 | 240
04 | 李云 | 3 | 100
06 | 吴兰 | 2 | 65
01 | 赵雷 | 3 | 189
12 | 赵六 | 0 | NULL
11 | 李四 | 0 | NULL
10 | 李四 | 0 | NULL
09 | 张三 | 0 | NULL
13 | 孙七 | 0 | NULL
02 | 钱电 | 3 | 210
07 | 郑竹 | 2 | 187
05 | 周梅 | 2 | 163
(12 行记录)
两个程序,逻辑上一个是先分组再联结,一个是先联结再分组,个人感觉先分组再联结效果会高一点吧?有机会测试下或者来大神指点下
知识点:
①、CAST(转换前的值 AS 想要转换的数据类型)
例如:SELECT CAST(‘0001’ AS INTEGER) AS int_col;
②、coalesce(数据1,数据2,数据3,……)
例如:
SELECT COALESCE(NULL,0) AS col_1,
COALESCE(NULL, 'test', NULL) AS col_2,
COALESCE(NULL, NULL, '2009-11-01') AS col_3;
col_1 | col_2 | col_3
-------+-------+------------
0 | test | 2009-11-01
(1 行记录)
③、聚合函数COUNT()、SUM()、AVG()、MAX()、MIN()