1. 程式人生 > >mysql 分組統計並列出百分比

mysql 分組統計並列出百分比

SELECT
	result,
	n,
	round( n / s * 100, 5 ) rat 
FROM
	(
	SELECT
		* 
	FROM
		( SELECT result, count( 1 ) n FROM sendsms_log GROUP BY result ) t1
		INNER JOIN ( SELECT count( 1 ) s FROM sendsms_log ) t2 ON 1 = 1 
	) t

其中“SELECT result, count( 1 ) n FROM sendsms_log GROUP BY result”是查出簡訊傳送結果分組統計,“SELECT count( 1 ) s FROM sendsms_log”查出所有記錄數,round( n / s * 100, 5 )計算百分比,保留5位小數。效果: