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
查詢結果如下所示