CASE 可能是 SQL 中被誤用最多的關鍵字之一。雖然你可能以前用過這個關鍵字來創建字段,但是它還具有更多用法。例如,你可以在 WHERE 子句中使用 CASE。
首先讓我們看一下 CASE 的語法。在一般的 SELECT 中,其語法如下:
SELECT
=
CASE
WHEN THEN
WHEN THEN
ELSE
END
在上面的代碼中需要用具體的參數代替尖括號中的內容。下面是一個簡單的例子:
USE pubs
GO
SELECT
Title,
'Price Range' =
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END
FROM titles
ORDER BY price
GO
這是 CASE 的典型用法,但是使用 CASE 其實可以做更多的事情。比方說下面的 GROUP BY 子句中的 CASE:
SELECT 'Number of Titles', Count(*)
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END
GO
你甚至還可以組合這些選項,添加一個 ORDER BY 子句,如下所示:
USE pubs
GO
SELECT
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END AS Range,
Title
FROM titles
GROUP BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END,
Title
ORDER BY
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END,
Title
GO
注意,為了在 GROUP BY 塊中使用 CASE,查詢語句需要在 GROUP BY 塊中重復 SELECT 塊中的 CASE 塊。
除了選擇自定義字段之外,在很多情況下 CASE 都非常有用。再深入一步,你還可以得到你以前認為不可能得到的分組排序結果集。