SQL:select case when 的用法

CASE 多是 SQL 中被誤用最多的關鍵字之一。雖然你可能之前用過這個關鍵字來建立字段,可是它還具備更多用法。例如,你能夠在 WHERE 子句中使用 CASE
首先讓咱們看一下 CASE 的語法。在通常的 SELECT 中,其語法以下:
html

SELECT <myColumnSpec> =
CASE
WHEN <A> THEN <somethingA>
WHEN <B> THEN <somethingB>
ELSE <somethingE>
END 

在上面的代碼中須要用具體的參數代替尖括號中的內容。下面是一個簡單的例子:
spa

 

 1 USE pubs
 2 GO
 3 SELECT
 4     Title,
 5     'Price Range' =
 6     CASE
 7         WHEN price IS NULL THEN 'Unpriced'
 8         WHEN price < 10 THEN 'Bargain'
 9         WHEN price BETWEEN 10 and 20 THEN 'Average'
10         ELSE 'Gift to impress relatives'
11     END
12 FROM titles
13 ORDER BY price
14 GO  

 

 

這是 CASE 的典型用法,可是使用 CASE 其實能夠作更多的事情。比方說下面的 GROUP BY 子句中的 CASEcode

 

 1 SELECT 'Number of Titles', Count(*)
 2 FROM titles
 3 GROUP BY
 4     CASE
 5         WHEN price IS NULL THEN 'Unpriced'
 6         WHEN price < 10 THEN 'Bargain'
 7         WHEN price BETWEEN 10 and 20 THEN 'Average'
 8         ELSE 'Gift to impress relatives'
 9     END
10 GO  

 

 

你甚至還能夠組合這些選項,添加一個 ORDER BY 子句,以下所示:htm

 

 1 USE pubs
 2 GO
 3 SELECT
 4     CASE
 5         WHEN price IS NULL THEN 'Unpriced'
 6         WHEN price < 10 THEN 'Bargain'
 7         WHEN price BETWEEN 10 and 20 THEN 'Average'
 8         ELSE 'Gift to impress relatives'
 9     END AS Range,
10     Title
11 FROM titles
12 GROUP BY
13     CASE
14         WHEN price IS NULL THEN 'Unpriced'
15         WHEN price < 10 THEN 'Bargain'
16         WHEN price BETWEEN 10 and 20 THEN 'Average'
17         ELSE 'Gift to impress relatives'
18     END,
19     Title
20 ORDER BY
21     CASE
22         WHEN price IS NULL THEN 'Unpriced'
23         WHEN price < 10 THEN 'Bargain'
24         WHEN price BETWEEN 10 and 20 THEN 'Average'
25         ELSE 'Gift to impress relatives'
26     END,
27     Title
28 GO  

 

 

注意:爲了在 GROUP BY 塊中使用 CASE,查詢語句須要在 GROUP BY 塊中重複 SELECT 塊中的 CASE 塊。

除了選擇自定義字段以外,在不少狀況下 CASE 都很是有用。再深刻一步,你還能夠獲得你之前認爲不可能獲得的分組排序結果集
blog

 

實際應用(代碼②處 ):http://www.cnblogs.com/dshore123/p/8057991.html排序

 

本文轉至:https://www.cnblogs.com/janes/archive/2009/03/23/1419527.htmlget

 

 

做者:DSHOREit

出處:http://www.cnblogs.com/dshore123/table

歡迎轉載,轉載務必說明出處。(若是本文對你有用,能夠點擊一下右下角的 推薦,謝謝!class

相關文章
相關標籤/搜索