国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

SQL集合函數中case when then 使用技巧

2020-07-25 13:21:02
字體:
來源:轉載
供稿:網友

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

假設數據庫有一張表名為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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 界首市| 岢岚县| 鄯善县| 韶关市| 大悟县| 嵊州市| 许昌市| 大丰市| 南丹县| 桓台县| 五台县| 福贡县| 宝丰县| 福海县| 罗定市| 文化| 澄城县| 江华| 安丘市| 麻城市| 陆川县| 三门县| 兴国县| 灌云县| 和静县| 鹤庆县| 雷州市| 神池县| 连平县| 福安市| 辽宁省| 安康市| 麻城市| 中牟县| 宁波市| 怀仁县| 平乡县| 贺州市| 隆林| 济阳县| 武城县|