How to SUM with COUNT function wih conditions How to SUM with COUNT function wih conditions codeigniter codeigniter

How to SUM with COUNT function wih conditions


You can use count(*)

SELECTCOUNT(CASE WHEN marital = 'divorced'   THEN 1 END) AS divorcestat,COUNT(CASE WHEN marital = 'married' THEN 1 END) AS marriedstat,COUNT(CASE WHEN marital = 'single' THEN 1 END) AS singlestat,COUNT(*) AS Total FROM status_tbl


You can add count(*) to the query

SELECTCOUNT(CASE WHEN marital = 'divorced'   THEN 1 END) AS divorcestat,COUNT(CASE WHEN marital = 'married' THEN 1 END) AS marriedstat,COUNT(CASE WHEN marital = 'single' THEN 1 END) AS singlestat,COUNT(*) AS total_statFROM status_tbl;

I hope that helps you.


You can also use a "table expression" to reuse the values you have already computed.

For example:

select  *,  divorcestat + marriedstat + singlestat as totalfrom (  SELECT  COUNT(CASE WHEN marital = 'divorced'   THEN 1 END) AS divorcestat,  COUNT(CASE WHEN marital = 'married' THEN 1 END) AS marriedstat,  COUNT(CASE WHEN marital = 'single' THEN 1 END) AS singlestat  FROM status_tbl) x

This can come in handy when the expression you use to compute values are complex and you don't want to repeat them in your query.