參考來源
----
本篇SQL真是高招,值得收藏!!
----
select count(*) as ct , CASE
WHEN (Pro_state= 1) THEN '待審'
WHEN (Pro_state= 2) THEN '已審'
WHEN (Pro_state= 3) THEN '辦理中'
WHEN (Pro_state= 4) THEN '已申退'
WHEN (Pro_state= 5) THEN '來信'
WHEN (Pro_state= 6) THEN '辦理完成'
WHEN (Pro_state= 7) THEN '未予立案'
end as pro_state
from vw_proposals_query where 1=1 GROUP BY pro_state
結果:
ct pro-state
30 辦理中
7 來信
1 辦理完成
5 未予立案
解讀:
查詢總數和pro_state 當 Pro_state= 1 時以 '待審' 替代表示
當 Pro_state= 2 時以 '已審' 替代表示
當 Pro_state= 3 時以 '辦理中' 替代表示
5、CASE 可能是 SQL 中被誤用最多的關鍵字之一。雖然你可能以前用過這個關鍵字來創建字段,但是它還具有更多用法。例如,你可以在 WHERE 子句中使用 CASE。
首先讓我們看一下 CASE 的語法。在一般的 SELECT 中,其語法如下:
SELECT {myColumnSpec} =
CASE
WHEN {A} THEN {somethingA}
WHEN {B} THEN {somethingB}
ELSE {somethingE}
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 都非常有用。再深入一步,你還可以得到你以前認為不可能得到的分組排序結果集。
沒有留言:
張貼留言