case具有兩種格式。簡單case函式和case搜尋函式。--簡單case函式case***
when'1'then'男'when'2'then'女'else'其他'end--case搜尋函式
casewhen*** ='1'then'男'when*** ='2'then'女'else'其他'end
這兩種方式,可以實現相同的功能。簡單case函式的寫法相對比較簡潔,但是和case搜尋函式相比,功能方面會有些限制,比如寫判斷式。
還有乙個需要注意的問題,case函式只返回第乙個符合條件的值,剩下的case部分將會被自動忽略。
--比如說,下面這段sql,你永遠無法得到「第二類」這個結果casewhencol_1in('a','b')then'第一類'whencol_1in('a')then'第二類'else'其他'end
下面我們來看一下,使用case函式都能做些什麼事情。
一,已知資料按照另外一種方式進行分組,分析。
有如下資料:(為了看得更清楚,我並沒有使用國家**,而是直接用國家名作為primary key)
中國600美國100加拿大100英國200法國300日本250德國200墨西哥50印度250
根據這個國家人口資料,統計亞洲和北美洲的人口數量。應該得到下面這個結果。
亞洲北美洲其他1100250700
想要解決這個問題,你會怎麼做?生成乙個帶有洲code的view,是乙個解決方法,但是這樣很難動態的改變統計的方式。如果使用case函式,sql**如下:
selectsum(population),casecountry
when'中國'then'亞洲'when'印度'then'亞洲'when'日本'then'亞洲'when'美國'then'北美洲'when'加拿大'then'北美洲'when'墨西哥'then'北美洲'else'其他'endfromtable_a
groupbycasecountry
when'中國'then'亞洲'when'印度'then'亞洲'when'日本'then'亞洲'when'美國'then'北美洲'when'加拿大'then'北美洲'when'墨西哥'then'北美洲'else'其他'end;
同樣的,我們也可以用這個方法來判斷工資的等級,並統計每一等級的人數。sql**如下;select
casewhensalary <= 500then'1'
whensalary > 500andsalary <= 600then'2'whensalary > 600andsalary <= 800then'3'whensalary > 800andsalary <= 1000then'4'elsenullendsalary_class,count(*)fromtable_agroupby
casewhensalary <= 500then'1'
whensalary > 500andsalary <= 600then'2'whensalary > 600andsalary <= 800then'3'whensalary > 800andsalary <= 1000then'4'
elsenullend;
二,用乙個sql語句完成不同條件的分組。
有如下資料
中國1340中國2260美國145美國255加拿大151加拿大249英國140英國260
按照國家和性別進行分組,得出結果如下中國340260美國4555加拿大5149英國4060
普通情況下,用union也可以實現用一條語句進行查詢。但是那樣增加消耗(兩個select部分),而且sql語句會比較長。
下面是乙個是用case函式來完成這個功能的例子selectcountry,
sum(casewhen*** ='1'then
populationelse0end),--男性人口sum(casewhen*** ='2'then
populationelse0end)--女性人口fromtable_a
groupbycountry;
這樣我們使用select,完成對二維表的輸出形式,充分顯示了case函式的強大。
三,在check中使用case函式。
在check中使用case函式在很多情況下都是非常不錯的解決方法。可能有很多人根本就不用check,那麼我建議你在看過下面的例子之後也嘗試一下在sql中使用check。
下面我們來舉個例子
公司a,這個公司有個規定,女職員的工資必須高於1000塊。如果用check和
case來表現的話,如下所示constraintcheck_salarycheck(casewhen*** ='2'
thencasewhensalary > 1000then1else0endelse1end= 1 )
如果單純使用check,如下所示constraintcheck_salarycheck
( *** ='2'andsalary > 1000 )
女職員的條件倒是符合了,男職員就無法輸入了。
Access中的SQL語句
access資料庫的sql語句教學 2009 07 01 20 50 47作者 網際網路瀏覽次數 229文字大小 大 中 小 引子 如何找到access資料庫的sql檢視 1 單擊下圖左側的 2 單擊上圖頂部的,彈出如下圖對話方塊 5 單擊 關閉 此時在選單中的檔案選單下面出現乙個sql的下拉框 6...
sql語句大全
建立資料庫 建立之前判斷該資料庫是否存在 if exists select from sysdatabases where name databasename drop database databasename gocreate database databasename 刪除資料庫 drop d...
SQL語句常用
1 新建資料庫aa createdatabaseaa 2 開啟資料庫aa opendatabaseaa 3 選擇aa為當前資料庫 setdatabasetoaa 4 修改資料庫aa modifydatabaseaa 5 刪除資料庫aa deletedatabaseaa 6 新建專案aa create...