Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Counting two things with different conditions

Tags:

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

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

and

SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ? 

I need to have a count for rows that have a certain address and certain port, and a SEPARATE count for rows that have a certain name.

I'm aware that I could do

SELECT (COUNT*) as count FROM table_name WHERE (address = ? AND port = ?) OR name = ? 

However that is a single count, and I need them to be separate so I can display a more accurate message to the user.

How might I go about doing this? Help would be appreciated!

like image 483
Jacob Brunson Avatar asked May 14 '12 00:05

Jacob Brunson


People also ask

Can I use two count in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

How do I count the number of different values in a column in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

How do you count by condition in SQL?

SQL COUNT() with HAVING The HAVING clause is used instead of WHERE clause with SQL COUNT() function. The GROUP BY with HAVING clause retrieves the result for a specific group of a column, which matches the condition specified in the HAVING clause.


2 Answers

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 
like image 164
Ezequiel Muns Avatar answered Sep 29 '22 17:09

Ezequiel Muns


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 = ? 
like image 34
bobwienholt Avatar answered Sep 29 '22 18:09

bobwienholt