tags:

views:

65

answers:

4

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?

A: 

to combine the results of queries with identical column formats, use UNION between them

SELECT w FROM x
UNION
SELECT y FROM z
brydgesk
Using `UNION DISTINCT` (which is what `UNION` means) is a bad idea here.
Mark Byers
+3  A: 

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;
macek
That's going to return 5 and 5; `count()` counts any value that isn't NULL, including empty strings
Michael Mrozek
@Michael Mrozek, yea I noticed he was using `!= ''` in his question and updated my post accordingly.
macek
+1  A: 
SELECT
    (SELECT COUNT(field1) FROM table) AS count1,
    (SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2
Mark Byers
A: 

Yet another way:

SELECT COUNT(field1), COUNT(IF(field2='', NULL, field2))
    FROM ...
outis