您好,登錄后才能下訂單哦!
本篇內容主要講解“mysql sum求和怎么使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“mysql sum求和怎么使用”吧!
mysql sum求和的方法:1、通過“select sum(value) as value from table where user_id”方式實現單一求和;2、通過嵌套語句多條件求和,語法如“(select sum(value) from table where type = 6 and type_son = 1) as xj0”。
MySQL SUM() 帶條件的求和方法與多條件的求和方法
一、單一的求和。
select sum(value) as value from table where user_id = 1 and type = 6 and type_son = 2
value 為求和的字段。
as 后面是 sum 求和后給它一個名稱。
二、SQL語句中嵌套語句多條件求和。
select
(select sum(value) from table where type = 6 and type_son = 1) as xj0,
(select sum(value) from table where type = 6 and type_son = 2) as xj1,
(select sum(value) from table where type = 3 and type_son = 3) as xj2,
(select sum(value) from table where type = 4 and type_son = 3) as xj3
from table where user_id = 1 limit 0,1
as 后面是 sum 求和后給它一個名稱,這樣就不會沖突。
三、與第二個一樣,但是不采取語句嵌套的方式求和,而是使用 sum 判斷求和。
select
sum(IF(type = 6 and type_son = 1,value,NULL)) as xj0,
sum(IF(type = 6 and type_son = 2,value,NULL)) as xj1,
sum(IF(type = 3 and type_son = 0,value,NULL)) as xj2,
sum(IF(type = 4 and type_son = 3,value,NULL)) as xj3
from table where user_id = 1
sum(IF('條件判斷','求和的字段','NULL不計算')) as '別名'
我覺得第三個的方式比前面兩個的方式要好。
YII 2.0 使用 SUM 求和
$v['alls_bonus'] = AccountingLog::find()
->select(["
sum( IF(type = 6 and type_son = 1,value,NULL) ) as xj0,
sum( IF(type = 6 and type_son = 4,value,NULL) ) as xj1,
sum( IF(type = 8 and type_son = 4,value,NULL) ) as xj2,
sum( IF(type = 3 and type_son = 1,value,NULL) ) as xj3
"])
->where(['user_id'=>1])
->asArray()
->one();
注意要在 select 里面加 ["sum........"],否則會報錯
到此,相信大家對“mysql sum求和怎么使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。