Question

I am stuck at MySQL CASE statement. I have following scenario and my table has below records:

Header_ID   |  Marks  
------------|----------  
55          |   0  
55          |   2  
66          |   5  
66          |   6  

I want to sum up the Marks, Header_ID wise. But for any given header, if the Marks is 0 (ZERO) then the SUM must be set to 0. So result should be as below:

Header_ID   | TOTAL_Marks  
------------|------------  
55          |    0 --> One of the Header has 0 marks so I must have 0 here.  
66          |    11 --> This is sum of Marks for Header_ID 66  

I tried using CASE statement with "SUM" function but getting the result as below:

SELECT  
    S.`headerid` AS `HEADER_ID`,  
    CASE  
      WHEN S.`mark` = 0 THEN 0  
      ELSE SUM(S.`mark`)  
    END AS `TOTAL_MARKS`  
FROM sample_db.sheet_data S  
GROUP BY S.`headerid`;  

RESULT:  
HEADER_ID  |  TOTAL_MARKS  
-----------|-------------  
55         |   2  --> Here it is not getting the expected value.  
66         |   11 --> This is sum of Marks for Header_ID 66  

SUM function is CASE statement returns value 2 and I want set this to 0.

Can anyone please help me here?

Was it helpful?

Solution

Here I use an IF to consider each value for mark. If the value is zero, the IF returns a 1, otherwise 0.

These are then passed to SUM to count how many values are zero. That sum is passed to another IF which returns 0 for any positive number of zero values, or the SUM of mark otherwise. This should function even if the sequence of values changes, for example when a zero value is not first for a particular headerid:

SELECT S.headerid as `HEADER_ID`,
    IF(SUM(IF(S.`mark` = 0, 1, 0)) > 0, 0, SUM(S.`mark`)) AS `TOTAL_MARKS`
FROM sample_db.sheet_data S
GROUP BY S.`headerid`;

OTHER TIPS

I pasted a wrong answer before. So I am editing my answer. Here is the complete demo :-

CREATE TABLE mark
(head_id INT, marks INT)

INSERT INTO mark VALUES (55,0)
INSERT INTO mark VALUES (55,2)
INSERT INTO mark VALUES (77,1)
INSERT INTO mark VALUES (77,0)

SELECT * FROM mark

enter image description here

SELECT
m1.head_id ,
SUM(CASE WHEN m1.head_id = m2.head_id THEN 0
     ELSE m1.marks END) AS mm
FROM
mark m1
LEFT JOIN
(SELECT DISTINCT head_id, NULL marks1 FROM mark WHERE marks = 0) m2
ON m1.head_id = m2.head_id
GROUP BY m1.head_id

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top