SQL中的if和case when用法

1 IF 函数

if (条件判断,符合条件值,不符合条件值)

2 case 函数

  • case函数使用1,switch case的效果
case 要判断的字段或者表达式
when 常量1 then 要显示的值1或者语句1;
when 常量2 then 要显示的值1或者语句2;
else 要显示的值n或者语句n;
end
  • 上述方式,常量对应case后面的字段或表达式,when后面是一个量,将常量与case后面的字段进行比较。而下述方式,when后面直接跟条件进行判断。
  • case 函数使用2: 多重if
case
when 条件1 then 要显示的值或者语句
else 要显示的值或者语句
end

case when 与group by 的连用

  • 两者连用可以实现行列转置
    现有如下一张表 sc

现在想把它转置,形成如下表

sid cid_01 cid_02 cid_03
01 80 90 99
02 ... ... ...
select sid, 
            MAX(case when cid = '01' then score else null end) 科目1,
	    MAX( case when cid = '02' then score else null end) 科目2,
	    MAX( case when cid = '03' then score else null end) 科目3				
from sc
GROUP BY sid

查询结果如下所示

原文地址:https://www.cnblogs.com/Vapriest/p/12985842.html