Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Count rows by field

Tags:

sql

mysql

All rows in a table have a type field which is either 0 or 1.

I need to count rows with 0 and with 1 in one query. So that result should look something like:

type0 | type1
------+------
1234  | 4211

How can this be implemented?

like image 978
Qiao Avatar asked Dec 13 '22 23:12

Qiao


2 Answers

select type, count(type) from tbl_table group by type;
like image 179
Will Avatar answered Jan 01 '23 20:01

Will


Lessee...

SELECT
    SUM(CASE type WHEN 0 THEN 1 ELSE 0 END) AS type0,
    SUM(CASE type WHEN 1 THEN 1 ELSE 0 END) AS type1
FROM
   tableX;

This has not been tested.

like image 28
staticsan Avatar answered Jan 01 '23 20:01

staticsan