SQL集合函數(shù)中case when then 使用技巧
那么在集合函數(shù)中它有什么用呢 ?
假設數(shù)據(jù)庫有一張表名為student的表。
如果現(xiàn)在要你根據(jù)這張表,查出江西省男女個數(shù),廣東省男生個數(shù),浙江省男女個數(shù) 怎么寫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()函數(shù)即根據(jù)給定的范圍和group by(統(tǒng)計方式) 而統(tǒng)計行數(shù)據(jù)的條數(shù)
我們一步步來理解上面語句
1. select sex from student (查詢數(shù)據(jù)表中的存在的男女條數(shù))
2.select sex, count (*) as num from student group by sex (查詢表中男女數(shù)量)
3.select sex ,province, count (*)as num from student group by sex,province (查詢各省男女數(shù)量)
重點來了,如果我把count(*) 中的 *號換成任一列名呢? 如count(province) 會怎樣?
4.select sex ,province, count (province)as num from student group by sex,province (查詢各省男女數(shù)量)
結果跟上圖一樣:這說明換不換都一樣。又有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
即統(tǒng)計男女數(shù)量范圍限定在浙江省 再精簡一下即下面
6.select sex, count ( case province when '浙江省' then '浙江省' end ) as 浙江省 from student group by sex
已經(jīng)接近我們的要求了,現(xiàn)在只要加上另幾個字段就是了
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
小結:當然實現(xiàn)有很多種方法 可以多個子查詢拼接起來也不無可厚非。我這只是一種思路
補充: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
相關文章
Sql Server中一個表2個字段關聯(lián)同一個表(代碼解決)
Sql Server中一個表2個字段關聯(lián)同一個表(代碼解決),需要的朋友可以參考一下2013-02-02SQL Server ltrim(rtrim()) 去不掉空格的原因分析
這篇文章主要介紹了SQL Server ltrim(rtrim()) 去不掉空格的原因分析,原因主要是因為中間存在回車符或者換行符,所以要先將此符號替換掉,具體示例代碼大家參考下本文2017-08-08OBJECTPROPERTY與sp_rename更改對象名稱的介紹
開發(fā)過程中,錯誤免不了。為了糾正錯誤與規(guī)范化。可以使用MS SQL Server的系統(tǒng)存儲過程sp_rename與OBJECTPROPERTY來更改重命名2012-01-01在Windows XP系統(tǒng)安裝SQL server 2000 企業(yè)版(圖解版)
今天在網(wǎng)上下載一個軟件,需要使用MS SQL,海波用的是 Windows XP Professional(專業(yè)) 版系統(tǒng),而SQL卻是企業(yè)版。安裝的時候提示我只能安裝客戶端,服務程序卻不能安裝。海波在網(wǎng)上搜索到了一些方法,設置成功了2014-07-07