MySQL: counting rows by field

All rows in the table have a field typethat is 0 or 1.

I need to count rows with 0 and with 1 in one query. Thus, the result should look something like this:

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

How can this be implemented?

+3
source share
4 answers
select type, count(type) from tbl_table group by type;
+8
source

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.

+3
source

You can use subqueries as scalar operands :

SELECT (SELECT COUNT(*) FROM table WHERE type = 0) AS type0,
       (SELECT COUNT(*) FROM table WHERE type = 1) AS type1;

Tested in MySQL as follows:

CREATE TABLE t (id INT NOT NULL AUTO_INCREMENT, type INT);

INSERT INTO t VALUES (NULL, 0);
INSERT INTO t VALUES (NULL, 0);
INSERT INTO t VALUES (NULL, 1);
INSERT INTO t VALUES (NULL, 1);
INSERT INTO t VALUES (NULL, 1);

SELECT (SELECT COUNT(*) FROM t WHERE type = 0) AS type0,
       (SELECT COUNT(*) FROM t WHERE type = 1) AS type1;

+-------+-------+
| type0 | type1 |
+-------+-------+
|     2 |     3 | 
+-------+-------+
1 row in set (0.00 sec)
+1
source

A result like this can be easily achieved:

Type  Count
-----------
type0 1234
type1 4221

You can use something like:

SELECT CONCAT('type', [type]) as Type, COUNT(*) as Count
FROM MyTable
GROUP BY Type
+1
source

Source: https://habr.com/ru/post/1738423/


All Articles