探討SQL Server中Case 的不同用法
2024-08-31 00:47:56
供稿:網(wǎng)友
 
case 可能是 sql 中被誤用最多的關(guān)鍵字之一。雖然你可能以前用過這個(gè)關(guān)鍵字來創(chuàng)建字段,但是它還具有更多用法。例如,你可以在 where 子句中使用 case。 首先讓我們看一下 case 的語法。在一般的 select 中,其語法如下: select <mycolumnspec> = case when <a> then <somethinga> when <b> then <somethingb> else <somethinge> end  在上面的代碼中需要用具體的參數(shù)代替尖括號(hào)中的內(nèi)容。下面是一個(gè)簡單的例子: 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 其實(shí)可以做更多的事情。比方說下面的 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  你甚至還可以組合這些選項(xiàng),添加一個(gè) 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 塊中重復(fù) select 塊中的 case 塊。 除了選擇自定義字段之外,在很多情況下 case 都非常有用。再深入一步,你還可以得到你以前認(rèn)為不可能得到的分組排序結(jié)果集。 轉(zhuǎn)自: http://www.g22.net/article/show.asp?id=688