Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - two counts with different WHERE in one query

Tags:

mysql

table

field1 field2
a       1
b
c       3
e       4
f

I need to count field1 and not empty field2 with on query:

SELECT COUNT(field1) FROM table
+
SELECT COUNT(field2) FROM table WHERE field2 != ''

result should be 5 and 3 in one query.

Is it possible?

like image 425
Qiao Avatar asked Apr 11 '10 00:04

Qiao


People also ask

How do I get counts of different values in the same 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 do multiple counts 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.

Can we give 2 WHERE statements in SQL query?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.

Can we use COUNT in WHERE clause in mysql?

1. SQL SELECT COUNT with WHERE clause. SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.


2 Answers

Easy as pie :)

select count(field1), count(field2)
from my_table

Result:

+--------+--------+
| field1 | field2 |
+--------+--------+
| 5      | 3      |
+--------+--------+

If the empty values in the field2 column are '' (empty strings) instead of actual NULL, you can try this:

select count(field1), sum(case when field2 != '' then 1 else 0 end)
from my_table;
like image 186
maček Avatar answered Oct 13 '22 20:10

maček


SELECT
    (SELECT COUNT(field1) FROM table) AS count1,
    (SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2
like image 40
Mark Byers Avatar answered Oct 13 '22 20:10

Mark Byers