case when的使用 sql深入學習

2021-07-14 02:48:37 字數 3175 閱讀 7316

最近接手的專案中需要對集體表中的男女人數做乙個統計,原來的實現是通過兩個查詢語句做到的——select * from student where ***='男',同樣也可以查詢到查詢到所有女生人數和總人數,暫且不說這樣會多少次連線資料庫造成資源的消耗和時間的浪費,就是前台的拼接資料也得費不少腦細胞吧,況且這麼low的辦法,肯定是有更加高效的方式的!

那麼就有了case when的用武之地,case when使這一業務效能上有了巨大優化,下面就見分曉!

業務背景:

需要查詢得到表中男生和女生各自的人數總和以及所有的人數;

表結構:

實現語句:

select

count(*) as number,

sum(

case ***

when '男' then

1else

0end

) as male,

sum(

case ***

when '女' then

1else

0end

) as female

from

student

結果:

這樣便一次拿到了所有的資料,減少了訪問資料庫的次數,降低了計算機的開銷成本,由於資料量小,自己並沒有做時間的檢測,資料量一旦足夠大肯定是會有明顯的效能改善的!

☆拓展:

1.已知資料按另一種方式分組、分析

--表結構:

--實現語句:

select

sum(population),

case country

when '中國' then

'亞洲'

when '印度' then

'亞洲'

when '日本' then

'亞洲'

when '美國' then

'北美洲'

when '加拿大' then

'北美洲'

when '墨西哥' then

'北美洲'

else

'其他'

endfrom

country

group by

case country

when '中國' then

'亞洲'

when '印度' then

'亞洲'

when '日本' then

'亞洲'

when '美國' then

'北美洲'

when '加拿大' then

'北美洲'

when '墨西哥' then

'北美洲'

else

'其他'

end;

--結果:

2.還有常見的對員工的工資按等級劃分;

--表結構:

--sql語句:

select

case

when salary <= 2000 then

'一'when salary > 2000

and salary <= 4000 then

'二'when salary > 4000

and salary <= 6000 then

'三'when salary > 6000

and salary <= 8000 then

'四'else

'其他'

end salary_class,

count(*)

from

salary

group by

case

when salary <= 2000 then

'一'when salary > 2000

and salary <= 4000 then

'二'when salary > 4000

and salary <= 6000 then

'三'when salary > 6000

and salary <= 8000 then

'四'else

'其他'

end;

--結果:

3.用乙個sql語句完成不同條件的分組

--表結構:

--sql語句:

select

country,

sum(

case

when *** = '男' then

population

else

0end

) as maleno,

sum(

case

when *** = '女' then

population

else

0end

) as femaleno

from

population

group by

country

--結果:

4.check中使用case 

總之,case when對查詢不同類別的資料會給我們提供很大的幫助,也確確實實會減少很多的消耗,提高響應速度!

SQL語句中case when的使用

根據使用者連續登陸的天數,增加不同的經驗值,如果通過select語句先查詢出來登陸天數,再通過天數去判斷應該增加多少經驗值的話,做多次查詢開啟多次事務效率肯定比較低,用儲存過程的話,感覺也沒有太大必要,所以還是用資料庫提供的方法 case when來解決好了 大家對if else語句可能都很熟悉,它...

sql 中case when 基礎使用

sql 語句中 case when then 簡單使用 因為表很簡單,就不為大家展示建表的 了 select from user 結果如圖 when 1 then 男 when 2 then 女 else 寵物 end 性別 from user u 查詢結果如下 從中可以看出我們的case函式是作為...

使用if或case when優化SQL

一 基本查詢語句展示優化 根據type查詢 select id,title,type from table where type 1 select id,title,type from table where type 2 用if優化 if expr,true,false select id,tit...