CASE 可能是 SQL 中被誤用最多的關鍵字之一
首先讓我們看一下 CASE 的語法
SELECT <myColumnSpec> =
CASE
WHEN <A> THEN <somethingA>
WHEN <B> THEN <somethingB>
ELSE <somethingE>
END
在上面的代碼中需要用具體的參數代替尖括號中的內容
USE pubs
GO
SELECT
Title
CASE
WHEN price IS NULL THEN
WHEN price <
WHEN price BETWEEN
ELSE
END
FROM titles
ORDER BY price
GO
這是 CASE 的典型用法
SELECT
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN
WHEN price <
WHEN price BETWEEN
ELSE
END
GO
你甚至還可以組合這些選項
USE pubs
GO
SELECT
CASE
WHEN price IS NULL THEN
WHEN price <
WHEN price BETWEEN
ELSE
END AS Range
Title
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN
WHEN price <
WHEN price BETWEEN
ELSE
END
Title
ORDER BY
CASE
WHEN price IS NULL THEN
WHEN price <
WHEN price BETWEEN
ELSE
END
Title
GO
注意
除了選擇自定義字段之外
From:http://tw.wingwit.com/Article/program/SQLServer/201311/22106.html