简体   繁体   中英

SUM of rows in My Sql with condition

My Data is

ID       SCORE
 1        55
 1        -1
 1        25
 1        -1
 1        -1
 1        35
 2        25
 2        -1 
 2        65
 2        55
 2        21
 2        -1

Now i want to add/sum the score of each id ignoring -1 and i am trying with this code which is not working

SELECT SUM(CASE when SCORE>-1 THEN SUM(SCORE) ELSE 0 END) 
FROM jbit WHERE htno='$id'

Here i am already using WHERE so how can i use another WHERE, if i use multiple Where in single query it may effect other processes.. please help me out

Help me out friends

if there is only two column then there is no need to use SUM, you can try below

SELECT id, IF(SCORE=-1,0,SCORE) AS scoreSum
FROM table1
GROUP BY id

Working DEMO

alternative ( not tested )

SELECT id, SUM(IF(SCORE=-1,0,SCORE)) AS scoreSum
FROM table1
WHERE htno =$id
GROUP BY id
SELECT SUM(score) AS score_sum
FROM jbit 
WHERE htno='$id'
  AND score <> -1 ;
SELECT SUM(`SCORE`)
FROM `jbit`
WHERE `htno` = '$id'
    `SCORE` > 0;

Though, I'd suggest you to change '$id' to just $id if the column type of htno is INTEGER .

SELECT SUM(score) FROM <tablename> WHERE score != -1

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