MySQL - Counting two things with different conditions

前端 未结 4 1620
忘掉有多难
忘掉有多难 2020-12-10 11:01

I want to count two things under different conditions in one query.

SELECT COUNT(*) AS count FROM table_name WHERE name = ?

and

<         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-10 11:41

    SELECT 
      COUNT( CASE WHEN n1 = 'J' THEN 1 END ) AS t1,
      COUNT( CASE WHEN n2 = 'C' THEN 1 END ) AS t2,
      COUNT( CASE WHEN n3 = 'K' THEN 1 END ) AS t3 
    FROM test
    

    Using COUNT(CASE...), you can get the count of two-column from single table, even when conditions for both are different (eg: Get count of J from n1 column and count of C from n2 column, and so on..)

    Table: test

    +----+----+----+----+
    | id | n1 | n2 | n3 |
    |----+----+----+----+
    |  1 | J  | C  | K  |
    |----+----+----+----+
    |  1 | J  | C  | F  |
    |----+----+----+----+
    |  1 | J  | K  | C  |
    |----+----+----+----+
    |  1 | K  | K  | C  |
    |----+----+----+----+
    

    Result:

    +----+----+----+
    | t1 | t2 | t3 |
    |----+----+----+
    |  3 | 2  | 1  |
    |----+----+----+
    

提交回复
热议问题