SQL集合函數(shù)中case when then 使用技巧建站知識
導(dǎo)讀:1建站知識我們都知道SQL中適用case when then來轉(zhuǎn)化數(shù)據(jù)庫中的信息 比如 select (case sex when 0 then企業(yè)網(wǎng)站建設(shè)網(wǎng)站推廣優(yōu)化seo。
那么在集合函數(shù)中它有什么用呢 ?
假設(shè)數(shù)據(jù)庫有一張表名為student的表。
如果現(xiàn)在要你根據(jù)這張表,查出江西省男女個數(shù),廣東省男生個數(shù),浙江省男女個數(shù) 怎么寫SQL語句?即要生成下結(jié)果表
答案是: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)計(jì)方式) 而統(tǒng)計(jì)行數(shù)據(jù)的條數(shù)
我們一步步來理解上面語句
1. select sex from student (查詢數(shù)據(jù)表中的存在的男女條數(shù))
2.select sex, count (*) as num from student group by sex (查詢表中男女?dāng)?shù)量)
3.select sex ,p網(wǎng)seo優(yōu)化趨勢rovince, count (*)as num from student group by sex,province (查詢各省男女?dāng)?shù)量)
重點(diǎn)來了,如果我把count(*) 中的 *號換成任一列名呢? 如count(province) 會怎樣?
4.select sex ,province, count (province)as num from student group by sex,province (查詢各省男女?dāng)?shù)量)
結(jié)果跟上圖一樣:這說明換不換都一樣。又有count (province)等價(jià)于 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)計(jì)男女?dā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 stu網(wǎng)站建設(shè)dent group by sex
小結(jié):當(dāng)然實(shí)現(xiàn)有很多種方法 可以多個子查詢拼接起來也不無可厚非。我這只是一種思路
補(bǔ)充:case when then 知識點(diǎn)
(1) select (case province when '浙江省' then '浙江' when '江西省' then '江西' end ) as 省份 from student
如果默認(rèn)范圍如果沒全包含則為空 像上圖的廣東省為空
(2)select (case province when '浙江省' then '浙江' when '江西省' then '江西' else province end ) as 省份 from student
聲明: 本文由我的SEOUC技術(shù)文章主頁發(fā)布于:2023-05-21 ,文章SQL集合函數(shù)中case when then 使用技巧建站知識主要講述使用技巧,函數(shù),SQL網(wǎng)站建設(shè)源碼以及服務(wù)器配置搭建相關(guān)技術(shù)文章。轉(zhuǎn)載請保留鏈接: http://www.bifwcx.com/article/web_3920.html
為你推薦與SQL集合函數(shù)中case when then 使用技巧建站知識相關(guān)的文章
-
通王TWCMS 2.0.3網(wǎng)站模板程序下載
(126)人喜歡 2024-01-15 -
Windows官方原版在哪里下載
(175)人喜歡 2024-01-15 -
WordPress網(wǎng)站模板發(fā)帖標(biāo)題顏色設(shè)置
(131)人喜歡 2024-01-07 -
修改discuz論壇帖子標(biāo)題80字符的長度限制
(249)人喜歡 2024-01-07 -
wordpress程序調(diào)用不帶超鏈接的Tag標(biāo)簽
(234)人喜歡 2024-01-05 -
網(wǎng)站在不同時(shí)期需調(diào)整內(nèi)容更新的方向
(112)人喜歡 2023-08-12