views:

77

answers:

5

I have a table that looks something like this:

id | firstperson | secondperson
1 | jane doe |
2 | bob smith | margie smith
3 | master shifu | madame shifu
4 | max maxwell | 

I'm trying to count all of the firstpersons + all of the secondpersons, if the secondpersons field isn't blank... Is there a way to do that?

+2  A: 
select sum(1 + case when secondperson <> '' then 1 else 0 end)
from MyTable
RedFilter
+5  A: 
SELECT SUM(CASE WHEN secondperson='' THEN 1 ELSE 2 END) FROM thetable;
Alex Martelli
A: 

I am not sure if this applies to Postgres or not, but in most databases, if we consider that there may be NULLS and that the question was really "if the secondperson field is not NULL", then you must explicitly include NULLS in the condition rather than the blank value.

JorgeLarre
A: 

SELECT SUM(CASE WHEN secondperson = '' OR secondperson IS NULL THEN 0 ELSE 2 END) FROM thetable;

StarShip3000
A: 

Assuming that blank means NULL, then in postgres, like in other systems, the count(field) will count the field only if it is not null and

SELECT count(*)+count(secondperson) FROM thetable;

will give the wanted result. (SQL syntax respect NULLs better then custom values for missing data. Also, off topic, any fields that have numbers in their name are candidates for design revision)

Unreason