應用場景: 需要根據(jù)印章的不同狀態(tài),統(tǒng)計不同狀態(tài)下印章數(shù)量。
剛開始百度,確實寫搜到了不同的答案,但只能怪自己對sql語法解讀不夠,還是沒寫出來,導致寫出了下面錯誤的寫法。
select b.corporateOrgName, b.corporateOrgGuid companyId, count(case when bc.ftype not in(1,2) then 1 else 0 end ) total, count(case when bc.ftype in(3,4,5) then 1 else 0 end ) usetotal, count(case when bc.ftype = 6 then 1 else 0 end ) saveTotal, count(case when bc.ftype = 7 then 1 else 0 end ) returnTotal from B_seal_cycle bc join B_seal b on bc.sealId = b.id where b.corporateOrgName like '%%' group by b.corporateOrgName,b.corporateOrgGuid
邏輯上通了,可就是怎么都得不到理想的接口,這樣寫統(tǒng)計的每一個數(shù)據(jù)都一樣呀。改變之后的正確寫法
select b.corporateOrgName, b.corporateOrgGuid companyId, count(case when bc.ftype not in(1,2) then 1 end ) total, count(case when bc.ftype in(3,4,5) then 1 end ) usetotal, count(case when bc.ftype = 6 then 1 end ) saveTotal, count(case when bc.ftype = 7 then 1 end ) returnTotal from B_seal_cycle bc join B_seal b on bc.sealId = b.id where b.corporateOrgName like '%%' group by b.corporateOrgName,b.corporateOrgGuid
你看出不同之處了嘛? 把else 0 去掉就得到了正確的結果。
遇到的問題
1、 對case when 語法,解讀有誤。
加了else 之后,總會對結果取 1 或 0.
2、 count函數(shù)都會對不管1 或 0 進行統(tǒng)計。
3、 當加了else 0 之后,可以通過sum函數(shù)進行統(tǒng)計。
也可以這樣寫
select b.corporateOrgName, b.corporateOrgGuid companyId, sum(case when bc.ftype not in(1,2) then 1 else 0 end ) total, sum(case when bc.ftype in(3,4,5) then 1 else 0 end ) usetotal, sum(case when bc.ftype = 6 then 1 else 0 end ) saveTotal, sum(case when bc.ftype = 7 then 1 else 0 end ) returnTotal from B_seal_cycle bc join B_seal b on bc.sealId = b.id where b.corporateOrgName like '%%' group by b.corporateOrgName,b.corporateOrgGuid
有問題,或者有更好的寫法,感謝留言指出。
補充知識:SQL語言中 執(zhí)行語句 DESC與DESCRIBE有什么區(qū)別?
DESCRIBE TABLE 用于列出指定表或視圖中的所有列。
DESCRIBE INDEX FOR TABLE 用于列出指定表的所有索引,
所以 DESCRIBE是用來顯示數(shù)據(jù)結構信息的;
而desc是descend ,是用于查詢出結果時候對結果進行排序,是降序排序。
DESCRIBE 是 SHOW COLUMNS FROM 的縮寫。
DESCRIBE 提供有關一個表的列信息。col_name 可以是一個列名或是一個包含 SQL 通配符字符 “%” 和 “_” 的字符串。沒有必要用引號包圍字符串。
一、describe命令用于查看特定表的詳細設計信息
例如為了查看guestbook表的設計信息,可用:
describe guestbook describe ol_user userid
二、可通過”show comnus”來查看數(shù)據(jù)庫中表的列名
有兩種使用方式:
show columns form 表名 from 數(shù)據(jù)庫名
或者:
show columns from 數(shù)據(jù)庫名.表名
三、用describe命令查詢具體列的信息
describe guestbook id 就是查詢guestbook中id字段的列信息
{DESCRIBE | DESC } tbl_name [col_name | wild]
DESCRIBE 是 SHOW COLUMNS FROM 的縮寫。
DESCRIBE 提供有關一個表的列信息。col_name 可以是一個列名或是一個包含 SQL 通配符字符 “%” 和 “_” 的字符串。沒有必要用引號包圍字符串。
mysql> desc ol_user username\G
四、判斷字段是否存在
mysql_connect( 'localhost' , 'root' , 'root' ); mysql_select_db( 'demo' ); $test = mysql_query( 'Describe cdb_posts first' ); $test = mysql_fetch_array($test);
$test[0]返回的是該字段的名稱,比如我要查詢first字段,返回的就是first
如果此字段不存在返回的就是NULL,通過這樣可以判斷一個字段是否存在
以上這篇在SQL中對同一個字段不同值,進行數(shù)據(jù)統(tǒng)計操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
標簽:惠州 呼和浩特 牡丹江 合肥 天津 沈陽 阿里 公主嶺
巨人網絡通訊聲明:本文標題《在SQL中對同一個字段不同值,進行數(shù)據(jù)統(tǒng)計操作》,本文關鍵詞 在,SQL,中,對,同一個,字段,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。