SUM returning different values when WHERE clause is changed

  • Hi,

    I have a strange issue. I have a table UserActivity with 2 columns, UserId and PointsAllocated. User = 2456, with 11 455 records. PointsAllocated is 0 for some records and values ( 7, 51, 200 etc) for other records.
    I have a simple query,  SELECT UserId, SUM(PointsAllocated) FROM UserActivity WHERE UserId = 2456 GROUP BY UserId and I'm getting 162 547.
    But where I write  SELECT UserId, SUM(PointsAllocated) FROM UserActivity WHERE UserId = 2456 AND PointsAllocated > 0 GROUP BY UserId I'm getting a different value, higher value, 337074.

    I want to understand why is it so, because when 0 is added to a number, a number doesn't change, why is that when I exclude the values I get more value returned.

  • mediacommentry - Tuesday, January 29, 2019 1:19 AM

    Hi,

    I have a strange issue. I have a table UserActivity with 2 columns, UserId and PointsAllocated. User = 2456, with 11 455 records. PointsAllocated is 0 for some records and values ( 7, 51, 200 etc) for other records.
    I have a simple query,  SELECT UserId, SUM(PointsAllocated) FROM UserActivity WHERE UserId = 2456 GROUP BY UserId and I'm getting 162 547.
    But where I write  SELECT UserId, SUM(PointsAllocated) FROM UserActivity WHERE UserId = 2456 AND PointsAllocated > 0 GROUP BY UserId I'm getting a different value, higher value, 337074.

    I want to understand why is it so, because when 0 is added to a number, a number doesn't change, why is that when I exclude the values I get more value returned.

    Run this:
    SELECT
     UserId,
     PositivePoints = SUM(CASE WHEN PointsAllocated > 0 THEN PointsAllocated ELSE 0 END),
     NegativePoints = SUM(CASE WHEN PointsAllocated < 0 THEN PointsAllocated ELSE 0 END)
    FROM UserActivity
    WHERE UserId = 2456
    GROUP BY UserId

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • You more than likely have negative numbers in that field.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply