Home / Databases / MySQL / How can I sum a field in mySQL only if it contains a value?
How can I sum a field in mySQL only if it contains a value?
Last updated: 02/08/2012
Sometimes on a query you'd like to tally how many records match a specific criteria, but also pull records that do not. The sum is just another field in the output, for a report let's say.
The secret is to use a conditional statement in my sql code. Here's an example:
select newsletter_id, sum(if(email_opened <> '0000-00-00 00:00:00',1,0)) as opened_sum,count(newsletter_id) as total_sent from emails group by newsletter_id;
In this case we are selecting all the records (emails sent), grouping by newsletter_id, and counting how many of each newsletter was sent. But, to count how many emails were actually opened, we can check the "email_opened" field - only those with a date filled in were opened. So using that conditional statement, opened emails count as 1, those not count as 0, giving us the totals we need.