7

Why wont the following work?

SELECT SUM(startUserThreads.newForStartUser)+SUM(endUserThreads.newForEndUser) AS numNew ...

It returns an empty string.

The following is returning 1 for my data set however:

SELECT SUM(startUserThreads.newForStartUser) AS numNew ...

How do I add the two sums correctly?

The whole thing:

SELECT t.*,
       COUNT(startUserThreads.id) + COUNT(endUserThreads.id)                     AS numThreads,
       SUM(startUserThreads.newForStartUser) + SUM(endUserThreads.newForEndUser) AS numNew
FROM   `folder` `t`
       LEFT OUTER JOIN `thread` `startUserThreads`
         ON ( `startUserThreads`.`startUserFolder_id` = `t`.`id` )
       LEFT OUTER JOIN `thread` `endUserThreads`
         ON ( `endUserThreads`.`endUserFolder_id` = `t`.`id` )
WHERE  user_id = :user

FYI, only two users can share a thread in my model. That should explain my column names

3
  • Can you show us the whole query? Jul 13, 2011 at 20:11
  • Neither of your queries are valid. Jul 13, 2011 at 20:12
  • added whole query. How is it not valid?
    – Jonah
    Jul 13, 2011 at 20:31

2 Answers 2

10
SELECT COALESCE(SUM(startUserThreads.newForStartUser),0)+COALESCE(SUM(endUserThreads.newForEndUser),0) AS numNew ...
4
  • It works.. but I don't get it.. We only give COALESCE one argument?
    – Jonah
    Jul 13, 2011 at 20:47
  • sorry second argument should be 0 Jul 13, 2011 at 20:50
  • ah cuz it trying to be adding an empty string to an integer!
    – Jonah
    Jul 13, 2011 at 20:52
  • realy it is a null not an empty string, sum only returns numeric values. so null + numeric yields null Jul 13, 2011 at 20:55
1

From the MySQL docs

SUM([DISTINCT] expr)

Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used in MySQL 5.0 to sum only the distinct values of expr.

SUM() returns NULL if there were no matching rows.

Aggregate (summary) functions such as COUNT(), MIN(), and SUM() ignore NULL values. The exception to this is COUNT(*), which counts rows and not individual column values.

Maybe try COALESCE( SUM(x), 0 ) + COALESCE( SUM(y), 0 )?

1
  • 2
    i thought sum will aggregate out nulls?
    – DForck42
    Jul 13, 2011 at 20:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.