Pat Mustard
Pat Mustard

Reputation: 1902

Calculate percentage of total rows where criteria is true

I want to count the number of rows that meet some criteria and calculate that as a percentage of total number of rows (in this case counting all of the id's).

Something like this:

((select count(error_flag) from MY_TABLE where error_flag == "TRUE" / count(id) from MY_TABLE) * 100) as "% ERROR"

Upvotes: 0

Views: 88

Answers (1)

James Scott
James Scott

Reputation: 1084

Please try the following:

CREATE TABLE errorTest (`error_flag` ENUM('TRUE','FALSE'));

INSERT INTO errorTest VALUES ('FALSE'), ('TRUE'), ('TRUE');

SELECT SUM(IF(error_flag = "TRUE", 1, 0)) / COUNT(*) `% ERROR` FROM errorTest;

Regards,

James

Upvotes: 2

Related Questions