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`)
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)