因爲網上沒有找到相關的解決方案,將這個方案拿出來供你們參考,下面以sum函數爲例mysql
建表、數據sql
CREATE TABLE `student` ( `name` varchar(10) DEFAULT NULL COMMENT '姓名', `sex` varchar(1) DEFAULT NULL COMMENT '性別', `id` varchar(2) DEFAULT NULL COMMENT '主鍵' PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8; INSERT INTO `eye`.`student` (`name`, `sex`, `age`) VALUES ('顧二嫂', '女', '30'); INSERT INTO `eye`.`student` (`name`, `sex`, `age`) VALUES ('宋江', '男', '48'); INSERT INTO `eye`.`student` (`name`, `sex`, `age`) VALUES ('林沖', '男', '35'); INSERT INTO `eye`.`student` (`name`, `sex`, `age`) VALUES ('嬌娘', '女', NULL);
mysql默認的sum函數處理結果函數
select sex as '性別',sum(age) as '總年齡' from student GROUP BY sex
如下是沒有忽略null的處理方案(對於值爲null的狀況,sum函數會把當前值當0處理,那麼咱們只要讓爲null的值大於0便可)code
select sex as '性別', (case when sum(IFNULL(age,1))>sum(age) then null else sum(age) end) as '總年齡' from student GROUP BY sex