1. 程式人生 > 資料庫 >在SQL中對同一個欄位不同值,進行資料統計操作

在SQL中對同一個欄位不同值,進行資料統計操作

應用場景: 需要根據印章的不同狀態,統計不同狀態下印章數量。

剛開始百度,確實寫搜到了不同的答案,但只能怪自己對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

邏輯上通了,可就是怎麼都得不到理想的介面,這樣寫統計的每一個數據都一樣呀。改變之後的正確寫法

select b.corporateOrgName,2) then 1 end ) total,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函式都會對不管1 或 0 進行統計。

3、 當加了else 0 之後,可以通過sum函式進行統計。

也可以這樣寫

select b.corporateOrgName,sum(case when bc.ftype not in(1,sum(case when bc.ftype in(3,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語言中 執行語句 DESC與DESCRIBE有什麼區別?

DESCRIBE TABLE 用於列出指定表或檢視中的所有列。

DESCRIBE INDEX FOR TABLE 用於列出指定表的所有索引,

所以 DESCRIBE是用來顯示資料結構資訊的;

而desc是descend ,是用於查詢出結果時候對結果進行排序,是降序排序。

DESCRIBE 是 SHOW COLUMNS FROM 的縮寫。

DESCRIBE 提供有關一個表的列資訊。col_name 可以是一個列名或是一個包含 SQL 萬用字元字元 “%” 和 “_” 的字串。沒有必要用引號包圍字串。

一、describe命令用於檢視特定表的詳細設計資訊

例如為了檢視guestbook表的設計資訊,可用:

describe guestbook describe ol_user userid

二、可通過”show comnus”來檢視資料庫中表的列名

有兩種使用方式:

show columns form 表名 from 資料庫名

或者:

show columns from 資料庫名.表名

三、用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中對同一個欄位不同值,進行資料統計操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。