Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

Tags:

mysql

I have a column 'hour' I have a column 'kind' (it can be 1,2 or 3)

I'd like to do something like:

SELECT count(id), SUM(hour) as totHour, SUM( IF ( kind = 1, 1, 0 ) ) as countKindOne 

or

SELECT count(id), SUM(hour) as totHour, COUNT( IF ( kind = 1 ) ) as countKindOne 

But mysql tell me I've an error... what's the error!?

Please see this stackoverflow topic: MySQL SUM IF field b = field a

.. I'm not able to reply this ...

like image 666
realtebo Avatar asked Oct 25 '12 19:10

realtebo


People also ask

Can I do a sum of a count in MySQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.

How do I use Countif in MySQL?

C) MySQL COUNT IF example You can use a control flow expression and functions e.g., IF , IFNULL , and CASE in the COUNT() function to count rows whose values match a condition. The IF() function returns 1 if the order's status is canceled, on hold or disputed, otherwise, it returns NULL .


2 Answers

You can use a CASE statement:

SELECT count(id),      SUM(hour) as totHour,      SUM(case when kind = 1 then 1 else 0 end) as countKindOne 
like image 155
Taryn Avatar answered Oct 14 '22 07:10

Taryn


you want something like:

SELECT count(id), SUM(hour) as totHour, SUM(kind=1) as countKindOne; 

Note that your second example was close, but the IF() function always takes three arguments, so it would have had to be COUNT(IF(kind=1,1,NULL)). I prefer the SUM() syntax shown above because it's concise.

like image 39
Gavin Towey Avatar answered Oct 14 '22 06:10

Gavin Towey