Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql switch case

I have a query structure like below, Im wondering if there is a way to the write the select queries as one using CASE statements or by some other means so that the values get inserted into the appropriate variables based on their values.

DECLARE passes INT;
DECLARE fails INT;
..

SELECT count(score)
INTO passes
  FROM scores
 WHERE score >= 40;

SELECT count(score)
INTO fails
  FROM scores
 WHERE score < 40;

Murdoch came up with a neat solution to this problem, I just had to make one change to it to put each of values in to there respective variables

SELECT * 
INTO   passes, fails 
FROM  (SELECT SUM(CASE 
                    WHEN score >= 40 THEN 1 
                    ELSE 0 
                  END) AS _passes, 
              SUM(CASE 
                    WHEN score < 40 THEN 1 
                    ELSE 0 
                  END) AS _fails 
       FROM   scores) AS x; 
like image 600
volting Avatar asked Dec 17 '22 16:12

volting


2 Answers

You can do this by doing a case for each score and returning 1 or 0. Then wrapping the whole thing in a SUM (not a COUNT) in effect adding one for each instance that matches the case.

SELECT 
SUM(CASE WHEN score >= 40 THEN 1 ELSE 0 END) AS passes, 
SUM(CASE WHEN score < 40 THEN 1 ELSE 0 END) AS fails 
FROM scores
like image 118
3urdoch Avatar answered Dec 19 '22 07:12

3urdoch


DECLARE tpasses INT;
DECLARE tfails INT;

SELECT 
    SUM(CASE WHEN score >= 40 THEN 1 ELSE 0 END) AS passes, 
    SUM(CASE WHEN score < 40 THEN 1 ELSE 0 END) AS fails 
INTO tpasses, tfails 
FROM scores
like image 29
Scott Avatar answered Dec 19 '22 05:12

Scott