mysql - How to write two SUMs with different conditions in a sql statement and find the difference between the two
阿神
阿神 2017-05-24 11:33:10
0
1
721

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

闭关修行中......

reply all (1)
洪涛

should be:

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

Or write more verbosely:

SUM(CASE WHEN type = 1 THEN score ELSE -score END)
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!