1. 程式人生 > >一條SQL語句實現查詢成績-60、60~80、+80的人數的方法

一條SQL語句實現查詢成績-60、60~80、+80的人數的方法

總結一下學到的一個SQL方法。下面我建立一個數據表:

在這裡插入圖片描述
SELECT * FROM students;
可以看到資料表中存在六條資料,如果使用傳統的查詢方法,我們需要三條SQL語句,分別是:

select count(*) from students where score<60;

select count(*) from students where score>80;

select count(*) from students where score between 60 and 80;

現在介紹三種使用一條SQL語句實現這個操作的方法:

case 0:

在這裡插入圖片描述

select sum(if(score<60 , 1,0)) as ‘<60’,sum(if(score between 60 and 80,1,0)) as ‘60~80’,sum(if(score >80,1,0)) as ‘>80’ from students;

case 1:
在這裡插入圖片描述

select if(score<60,’<60’,if(score between 60 and 80,‘60~80’,’>80’)) as rang,count(*) from students group by if(score<60,’<60’,if(score between 60 and 80,‘60~80’,’>80’));

case 2:
在這裡插入圖片描述

select score,count(*) from students group by case when score<60 then ‘<60’ when score between 60 and 80 then ‘60~80’ else ‘>80’ end;

為什麼能夠用三條簡單的語句解決的資料庫查詢我們要使用這麼複雜的SQL語句呢?

這個可不是為了裝逼;

因為每一條SQL語句事實上都是掃描一次資料庫,把這三條SQL語句寫成一條符合邏輯的SQL語句,實際上只需要掃描一遍資料庫,而這大大節省了系統開銷;

因為在處理商用資料庫的時候,動輒幾千萬上億的資料量,一次全表掃描就可能幾個小時,這個時候複雜結構的SQL語句的優勢就表現出來了;​