提要:这个问题是我也在笔试的时候出现的问题,当初看到题目,想到很多方法,当感觉脚本太过复杂,笔试完毕,在网上查询之后,整理了一下,写在这里与大家一起讨论学习。
1、题目:
张三和李四的成绩表(CJ)如下:
------------------------------------
name subject result
张三 语文 80
张三 数学 90
张三 物理 85
李四 语文 85
李四 数学 92
李四 物理 82
问题1:如何输出如下的交叉表?
------------------------------------
姓名 语文 数学 物理
张三 99 90 85
李四 85 92 82
问题2:当要增加“总计”列:"合计总分"时呢?
---------------------------------------------------------------------
姓名 合计总分 语文 数学 物理
张三 260 99 90 85
李四 241 85 92 82
2、问题1解决方法:
select name “姓名”,
sum(case when a.subject = '语文' then result else null end) as '语文',
sum(case when a.subject = '数学' then result else null end) as '数学',
sum(case when a.subject = '英语' then result else null end) as '英语'
from CJ a
group by name;
3、问题2解决方法:
select name,sum(a.result) as "合计总分",
sum(case when a.subject='语文' then result else null end) as "语文",
sum(case when a.subject='数学' then result else null end) as "数学",
sum(case when a.subject='英语' then result else null end) as "英语"
from CJ a
group by name;
注:用NULL而不用0是有道理的,假如用0,虽然求和函数SUM可以取到正确的数,但类似COUNT函数(取记录个数),
结果就不对了,因为Null不算一条记录,而0要算,同理空字串("")也是这样,总之在这里应该用NULL,这样任何函数都没问题。