CASE 的使用

 

T-SQL CASE 的用法範例如下

--範例一、
select Name, age,
case
    when age = 30 then '三十而立' 
    when age = 40 then '四十不惑' 
end 年齡層
from 
(
    SELECT 1 AS No, 'Bill' AS Name, 30 AS age
    UNION
    SELECT 2 AS No, 'Mary' AS Name, 40 AS age
    UNION
    SELECT 3 AS No, 'Json' AS Name, 30 AS age
    UNION
    SELECT 4 AS No, 'Tim' AS Name, 40 AS age
) p

–範例二、
select Name, age,
case age
when 30 then ‘三十而立’
when 40 then ‘四十不惑’
end 年齡層
from
(
SELECT 1 AS No, ‘Bill’ AS Name, 30 AS age
UNION
SELECT 2 AS No, ‘Mary’ AS Name, 40 AS age
UNION
SELECT 3 AS No, ‘Json’ AS Name, 30 AS age
UNION
SELECT 4 AS No, ‘Tim’ AS Name, 40 AS age
) p

–範例三、
select Name, age,
case
when age <= 30 then ‘年輕人’ else ‘中年人’
end 年齡層
from
(
SELECT 1 AS No, ‘Bill’ AS Name, 30 AS age
UNION
SELECT 2 AS No, ‘Mary’ AS Name, 40 AS age
UNION
SELECT 3 AS No, ‘Json’ AS Name, 30 AS age
UNION
SELECT 4 AS No, ‘Tim’ AS Name, 40 AS age
) p

執行結果如下