MySQL - Counting two things with different conditions

前端 未结 4 1606
忘掉有多难
忘掉有多难 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:37
    SELECT SUM(CASE WHEN Name = ? THEN 1 ELSE 0 END) as name_match
           , SUM(CASE WHEN Address = ? AND Port = ? THEN 1 ELSE 0 END) as address_match
    FROM table_name
    WHERE (address = ? AND port = ?) OR name = ?
    
    0 讨论(0)
  • 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  |
    |----+----+----+
    
    0 讨论(0)
  • 2020-12-10 11:45

    What about simply:

    SELECT 
        SUM(IF(name = ?, 1, 0)) AS name_count,
        SUM(IF(address = ? AND port = ?, 1, 0)) AS addr_count
    FROM 
        table_name
    
    0 讨论(0)
  • 2020-12-10 11:45

    Might be easiest just to do a Union:

    SELECT COUNT(*) AS count FROM table_name WHERE name = ? 
        GROUP BY name
    UNION ALL
    SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ?
        GROUP BY address, port
    
    0 讨论(0)
提交回复
热议问题