coalesce()函数含义为:
返回其中第一个非null表达式的值,若所有表达式都为null,则返回null。
例:select coalesce(subject,grade,’’) from table
查询table表中的列subject,如果其不为null则返回,为null则查询grade,查询grade仍未null则返回空字符。(表中需要存在subject与grade两列)
行列转换:
有一个表为:
name subject score
张三 数学 100
张三 英语 90
张三 语文 80
要将其转换为
姓名 数学 英语 语文
张三 100 90 80
代码实现:
select name as 姓名,
max(case when subject =’数学’ then score end)as 数学
max(case when subject =’英语’ then score end)as
英语
max(case when subject = ‘语文’ then score end)as语文
from test group by name
group by应用于聚合函数中例如sum,max。