search

Home  >  Q&A  >  body text

mysql - How to write two SUMs with different conditions in a sql statement and find the difference between the two

The table used in my business is the user's points log table. The fields are user id, point type (added to 1 and reduced to 2), points, timestamp
I need to calculate the total points earned by the user every day
I initially summed up the plus points and minus points separately, and then looped the array to find the difference in the back-end program. This was extremely inefficient. I wanted to write it out in the sql statement. How to write it? Use case then to report an error

SUM(CASE type=1 THEN `score` ELSE 0-`score`)
阿神阿神2824 days ago832

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-24 11:35:10

    should be:

    SUM(IF(type = 1, score, -score))
    

    Or write more verbosely:

    SUM(CASE WHEN type = 1 THEN score ELSE -score END)

    reply
    0
  • Cancelreply