简体   繁体   中英

MySQL counting points

I have this (simplified) runs table where each finished run counts as a point:

| email | finished |
|-------|----------|
|    a  |     1    |
|    a  |     1    |
|    a  |     0    |
|    b  |     1    |
|    c  |     0    |

I have this

SELECT *, COUNT( * ) AS points 
FROM  `runs` 
WHERE finished IS TRUE
GROUP BY email

Result is:

| email |  points  |
|-------|----------|
|    a  |     2    |
|    b  |     1    |

The problem is that I also want the information about C, which has 0 points as C hasn't finished a run yet

Expected result:

| email |  points  |
|-------|----------|
|    a  |     2    |
|    b  |     1    |
|    c  |     0    |

Remove where clause :

SELECT r.email, SUM( finished IS TRUE ) AS points 
FROM  `runs` r 
GROUP BY email;

Yes you can remove filtration also in sum() :

SELECT r.email, SUM(finished) AS points 
FROM  `runs` r 
GROUP BY email;

Use sum instead:

SELECT email, sum(finished) AS points 
  FROM  `runs` 
  GROUP BY email
SELECT email, sum(finished) AS points FROM  `runs` GROUP BY email;

参考: https ://www.w3schools.com/sql/sql_count_avg_sum.asp http://www.mysqltutorial.org/mysql-boolean/

Convert your finished into int type and do the sum.

    SELECT *, sum( cast(finished as int) ) AS points 
    FROM  `runs` 
    GROUP BY email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM