1. 程式人生 > >select case when where having用法

select case when where having用法

CASE 可能是 SQL 中被誤用最多的關鍵字之一。雖然你可能以前用過這個關鍵字來建立欄位,但是它還具有更多用法。例如,你可以在 WHERE 子句中使用 CASE。

首先讓我們看一下 CASE 的語法。在一般的 SELECT 中,其語法如下:

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

在上面的程式碼中需要用具體的引數代替尖括號中的內容。

[color=green]example one:[/color]
select c.* from (select t.name, sum(t.fenshu) total, avg(t.fenshu) perscore, count(*) courses from (select name, kechen, (case when fenshu<'80' then '0' else fenshu end) fenshu from course) t group by name) c where c.perscore >= 80

[b]example one data structure[/b]:
name kechen fenshu
test 語文 81
test 數學 83
test 英語 92

[color=green]example two:[/color]
select t.* from (select name, (case when yuwen IS NULL then '80' else yuwen end) as yuwen, (case when shuxue IS NULL then '80' else shuxue end) as shuxue, (case when yingyu IS NULL then '80' else yingyu end) as yingyu from score) t where t.yuwen>='80' and t.shuxue>='80' and t.yingyu>='80'

[b]example two data structure:[/b]
name yuwen shuxue yingyu
test 81 97 87

example three:
select
reg.NAME,
reg.END_TIME,
reg.DURATION,
(case reg.status
when 'COMPLETE' then 1
else 0
end) as complete,
(case reg.status
when 'INCOMPLETE' then 1
else 0
end) as incomplete,
(case reg.status
when 'ERROR' then 1
else 0
end) as error,
(case reg.status
when 'TIMEOUT' then 1
else 0
end) as timeout,
(case reg.status
when 'INFLIGHT' then 1
when 'ORPHANED' then 1
when 'PENDING' then 1
when 'RECONCILE' then 1
else 0
end) as inflight
from
TM_TRANSACTION_REGISTRY reg


下面是一個簡單的例子:

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 都非常有用。再深入一步,你還可以得到你以前認為不可能得到的分組排序結果集。

[color=green]“Where” 是一個約束宣告,使用Where來約束來之資料庫的資料,Where是在結果返回之前起作用的。[/color]

[color=green]“Having”是一個過濾宣告,當查詢返回結果集以後對查詢結果進行過濾操作。[/color]