sql語法case用法

wenmin311發表於2008-02-29
關鍵詞: informix,sql,ca

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

對於informix不能用以上形式,可以如下:

USE pubs

GO

SELECT

Title,

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

Price Range

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

對於informix中形式有所不同,例子

select

case when td_acc1_no[1,3]='610' then get_contrast(td_acc1_no)

else get_contrast(td_td_acct_no)

end sx_acct_no

, sum(td_actu_amt) sx_bal

from dcc_tdacnacn where td_td_acct_no in ('6107111001014107111000050182',

'6107111001014107111000050168')

group by 1

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

除了選擇自定義欄位之外,在很多情況下 CASE 都非常有用。再深入一步,你還可以得到你以前認為不可能得到的分組排序結果集。

相關文章