MySQL - 在一个查询中按两列计数

时间:2018-04-10 19:01:00

标签: mysql count

这是我的表:

| ID | TYPE |
|  1 |  1   |
|  2 |  1   |
|  3 |  1   |
|  4 |  0   |
|  5 |  0   |

现在,我想计算TYPE = 1时存在多少条记录,以及TYPE = 0时存在多少条记录?是否可以?

我知道,我可以通过两个查询来完成:

SELECT COUNT(*) AS all_zero FROM `table WHERE type = 0;
SELECT COUNT(*) AS all_one FROM `table WHERE type = 1;

但我希望在一个查询中执行此操作。 有可能吗?

3 个答案:

答案 0 :(得分:3)

GROUP BY就是这样做的:

SELECT type, COUNT(*) AS count_of_type FROM my_table GROUP BY type

这会为您提供多行,每种类型一行:

+------+---------------+
| type | count_of_type |
+------+---------------+
|    0 |             2 |
|    1 |             3 |
+------+---------------+

如果您有更多类型,但只想要0和1,则可以添加HAVING子句:

SELECT type, COUNT(*) AS count_of_type FROM my_table GROUP BY type HAVING type IN (0,1)

如果您希望在单个结果集行中获得不同的计数,请参阅the answer by spencer7593

答案 1 :(得分:3)

条件聚合会这样做......

SELECT SUM(t.type=0)          AS cnt_zero
     , SUM(t.type=1)          AS cnt_one
     , SUM(t.type IN (0,1))   AS cnt_one_and_zero
     , SUM(1)                 AS cnt_all
  FROM mytable t
;

请注意,type=0type=1的使用是特定于MySQL的简写,其他数据库可能不接受。

如果我们忽略NULL值的处理,这基本上等同于

SELECT SUM(IF( t.type=0        ,1,0))   AS cnt_zero
     , SUM(IF( t.type=1        ,1,0))   AS cnt_one
     , SUM(IF( t.type IN (0,1), 1,0))   AS cnt_one_and_zero
     , SUM(1)                           AS cnt_all
  FROM mytable t
;

更符合ANSI标准的等效

SELECT SUM(CASE WHEN t.type=0        THEN 1 ELSE 0 END)  AS cnt_zero
     , SUM(CASE WHEN t.type=1        THEN 1 ELSE 0 END)  AS cnt_one
     , SUM(CASE WHEN t.type IN (0,1) THEN 1 ELSE 0 END)  AS cnt_one_and_zero
     , SUM(1)                                            AS cnt_all
  FROM mytable t
;

为了获得与本答案中第一个查询相同的NULL值处理和相同的结果,我们可以这样写:

SELECT SUM(CASE WHEN t.type=0        THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END)  AS cnt_zero
     , SUM(CASE WHEN t.type=1        THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END)  AS cnt_one
     , SUM(CASE WHEN t.type IN (0,1) THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END)  AS cnt_one_and_zero
     , SUM(1)                                                                          AS cnt_all
  FROM mytable t
;

在所有这些中,主题保持不变:我们正在汇总条件的结果。 Aka 条件聚合

答案 2 :(得分:1)

很简单:

SELECT
    `type`,
    count(*) as `typecount`
FROM table
GROUP BY `type`