case when then 與 count聯合使用


我們都知道SQL中適用case when then來轉化數據庫中的信息

      比如  select (case sex when 0 then '男' else '女' end) AS sex  from studentInfo

那么在集合函數中它有什么用呢 ?

 

假設數據庫有一張表名為student的表。

如果現在要你根據這張表,查出江西省男女個數,廣東省男生個數,浙江省男女個數 怎么寫SQL語句?

答案是:

select sex ,

  count ( case province when '廣東省' then '廣東省' end )as 廣東省 ,

  count ( case province when '江西省' then '江西省' end )as 江西省 ,

  count ( case province when '浙江省' then '浙江省' end )as 浙江省

  from student group by sex

count()函數即根據給定的范圍和group by(統計方式) 而統計行數據的條數

我們一步步來理解上面語句

1.  select sex from student (查詢數據表中的存在的男女條數)

2.select sex, count (*) as num from student group by sex  (查詢表中男女數量)

3.select sex ,province, count (*)as num from student group by sex,province (查詢各省男女數量)

  重點來了,如果我把count(*) 中的 *號換成任一列名呢? 如count(province) 會怎樣?

4.select sex ,province, count (province)as num from student group by sex,province (查詢各省男女數量)

  又有count (province)等價於 count(case province when '浙江省' then '浙江省' else province end )

  但是如果我們縮小范圍呢即count(case province when '浙江省' then '浙江省' end ) 那么請看下面

5.select sex ,province, count ( case province when '浙江省' then '浙江省' end )as num from student group by sex,province

  即統計男女數量范圍限定在浙江省 再精簡一下即下面

6.select sex, count ( case province when '浙江省' then '浙江省' end ) as 浙江省 from student group by sex

  已經接近我們的要求了,現在只要加上另幾個字段就是了

7.select sex ,count ( case province when '廣東省' then '廣東省' end )as 廣東省 ,count ( case province when '江西省' then '江西省' end )as 江西省 ,count ( case province when '浙江省' then '浙江省' end )as 浙江省 from student group by sex

  小結:當然實現有很多種方法 可以多個子查詢拼接起來也不無可厚非。我這只是一種思路

  補充:case when then 知識點

  (1) select (case province when '浙江省' then '浙江' when '江西省' then '江西' end  ) as 省份 from student

  如果默認范圍如果沒全包含則為空 

  (2)select (case province when '浙江省' then '浙江' when '江西省' then '江西' else province end  ) as 省份 from student

 

Eg:查找每個訂單中的報告情況

select id,ORDER_ID, count(case STATUS when 'F' then true end ) as '已發送報告' , count(case STATUS when 'D' then true end ) as '已生成報告', count(case STATUS when 'T' then true end ) as '未生成報告', max(SERVICE_CNT) as '共計服務次數' from APP_NUTRITION_SERVICE_DETAIL where DELETE_MARK='N' and ORDER_ID in(2016042501,2016042502) group by ORDER_ID
結果:array
( [0] => Array ( [id] => 6 [ORDER_ID] => 2016042501 [已發送報告] => 4 [已生成報告] => 1 [未生成報告] => 0 [共計服務次數] => 5 ) [1] => Array ( [id] => 8 [ORDER_ID] => 2016042502 [已發送報告] => 1 [已生成報告] => 1 [未生成報告] => 0 [共計服務次數] => 2 )

 

 

selectid,ORDER_ID,count(caseSTATUSwhen'F'thentrueend)as'已發送報告',count(caseSTATUSwhen'D'thentrueend)as'已生成報告',count(caseSTATUSwhen'T'thentrueend)as'未生成報告',max(SERVICE_CNT)as'共計服務次數'fromAPP_NUTRITION_SERVICE_DETAILwhereDELETE_MARK='N'andORDER_IDin(2016042501,2016042502)groupbyORDER_ID


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM