表中的所有行都有type
字段,该字段为0或1。
我需要在一个查询中计算0和1的行数。所以结果应该类似于:
type0 | type1
------+------
1234 | 4211
如何实施?
答案 0 :(得分:8)
select type, count(type) from tbl_table group by type;
答案 1 :(得分:3)
...承租人
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;
未已经过测试。
答案 2 :(得分:1)
您可能想要使用subqueries as scalar operands:
SELECT (SELECT COUNT(*) FROM table WHERE type = 0) AS type0,
(SELECT COUNT(*) FROM table WHERE type = 1) AS type1;
在MySQL中测试如下:
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)
答案 3 :(得分:1)
这样的结果很容易实现:
Type Count
-----------
type0 1234
type1 4221
您可以使用以下内容:
SELECT CONCAT('type', [type]) as Type, COUNT(*) as Count
FROM MyTable
GROUP BY Type