查詢生成統計列表:sql
case具備兩種格式。簡單case函數和case搜索函數。函數
--簡單case函數spa
case sexcode
when '1' then '男'ci
when '2' then '女'it
else '其餘' endio
--case搜索函數table
case when sex = '1' then '男'class
when sex = '2' then '女'date
else '其餘' end
這兩種方式,能夠實現相同的功能。簡單case函數的寫法相對比較簡潔,可是和case搜索函數相比,功能方面會有些限制,好比寫斷定式。
還有一個須要注重的問題,case函數只返回第一個符合條件的值,剩下的case部分將會被自動忽略。
--好比說,下面這段sql,你永遠沒法獲得「第二類」這個結果
case when col_1 in ( 'a', 'b') then'第一類'
when col_1 in ('a') then '第二類'
else'其餘'end
下面咱們來看一下,使用case函數都能作些什麼事情。
一,已知數據按照另一種方式進行分組,分析。
有以下數據:(爲了看得更清楚,我並無使用國家代碼,而是直接用國家名做爲primary key)
國家(country) |
人口(population) |
中國 |
600 |
美國 |
100 |
加拿大 |
100 |
英國 |
200 |
法國 |
300 |
日本 |
250 |
德國 |
200 |
墨西哥 |
50 |
印度 |
250 |
根據這個國家人口數據,統計亞洲和北美洲的人口數量。應該獲得下面這個結果。
洲 |
人口 |
亞洲 |
1100 |
北美洲 |
250 |
其餘 |
700 |
想要解決這個問題,你會怎麼作?生成一個帶有洲code的view,是一個解決方法,可是這樣很難動態的改變統計的方式。
假如使用case函數,sql代碼以下:
select sum(population),
case country
when '中國' then'亞洲'
when '印度' then'亞洲'
when '日本' then'亞洲'
when '美國' then'北美洲'
when '加拿大' then'北美洲'
when '墨西哥' then'北美洲'
else '其餘' end
from table_a
group by case country
when '中國' then'亞洲'
when '印度' then'亞洲'
when '日本' then'亞洲'
when '美國' then'北美洲'
when '加拿大' then'北美洲'
when '墨西哥' then'北美洲'
else '其餘' end;
一樣的,咱們也能夠用這個方法來斷定工資的等級,並統計每一等級的人數。sql代碼以下;
select
case when salary <= 500 then '1'
when salary > 500 and salary <= 600 then '2'
when salary > 600 and salary <= 800 then '3'
when salary > 800 and salary <= 1000 then '4'
else null end salary_class,
count(*)
from table_a
group by
case when salary <= 500 then '1'
when salary > 500 and salary <= 600 then '2'
when salary > 600 and salary <= 800 then '3'
when salary > 800 and salary <= 1000 then '4'
else null end;
二,用一個sql語句完成不一樣條件的分組。
有以下數據
國家(country) |
性別(sex) |
人口(population) |
中國 |
1 |
340 |
中國 |
2 |
260 |
美國 |
1 |
45 |
美國 |
2 |
55 |
加拿大 |
1 |
51 |
加拿大 |
2 |
49 |
英國 |
1 |
40 |
英國 |
2 |
60 |
按照國家和性別進行分組,得出結果以下
國家 |
男 |
女 |
中國 |
340 |
260 |
美國 |
45 |
55 |
加拿大 |
51 |
49 |
英國 |
40 |
60 |
普通狀況下,用union也能夠實現用一條語句進行查詢。可是那樣增長消耗(兩個select部分),並且sql語句會比較長。
下面是一個是用case函數來完成這個功能的例子
select country,
sum( case when sex = '1' then
population else 0 end), --男性人口
sum( case when sex = '2' then
population else 0 end) --女性人口
from table_a
group by country;
這樣咱們使用select,完成對二維表的輸出形式,充分顯示了case函數的強大。
三,在check中使用case函數。
在check中使用case函數在不少狀況下都是很是不錯的解決方法。可能有不少人根本就不用check,那麼我建議你在看過下面的例子以後也嘗試一下在sql中使用check。
下面咱們來舉個例子
公司a,這個公司有個規定,女職員的工資必須高於1000塊。假如用check和case來表現的話,以下所示
constraint check_salary check
( case when sex = '2'
then case when salary > 1000
then 1 else 0 end
else 1 end = 1 )
假如單純使用check,以下所示
constraint check_salary check
( sex = '2' and salary > 1000 )
女職員的條件卻是符合了,男職員就沒法輸入了。