0

I'm using this MySQL query

SELECT COUNT(pros_a) + COUNT(pros_b) + COUNT(pros_c) + COUNT(pros_d) + COUNT(pros_e) AS pros_total FROM my_table WHERE contentid = 'id'

to count and sum fields in each column. But this returns ALL fields (full and empty). I want to count only filled fields, excluding empty fields. How can I do that? Just a little bit... confused! :)

Any help would be very appreciated! Thanks

EDIT:

my_table

pros_a   pros_b   pros_c   pros_d   pros_e
-------  ------   ------   ------   ------
good     (empty)  good     good     (empty)

expected result

pros_total
----------
3
3
  • 1
    What is an empty field for you? Commented Mar 6, 2012 at 14:44
  • Can you post sample data and expected output? Commented Mar 6, 2012 at 14:48
  • @Salman A Yeah, sorry. Just edited. Commented Mar 6, 2012 at 15:04

3 Answers 3

1

The COUNT(column) function does not count fields that are NULL. It counts empty (zero-length) strings though.

You can change these into:

COUNT( CASE WHEN column <> '' THEN column END )

or:

SUM(column <> '')

The last works in MySQL because TRUE is evaluated as 1 and FALSE as 0.

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT COUNT(DISTINCT pros_a) + COUNT(DISTINCT pros_b) + COUNT(DISTINCT pros_c) + COUNT(DISTINCT pros_d) + COUNT(DISTINCT pros_e) FROM my_table WHERE contentid = 'id'

The above one should work.

Comments

0

Use where condition for empty fields, for example WHERE pros_a != '' or pros_a != '0' if is NULL. pros_a != '' AND pros_b != ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.