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?
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.
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.
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.
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.
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;
SELECT
(SELECT COUNT(field1) FROM table) AS count1,
(SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With