Jump to content

CASE, WHEN, ELSE in a SELECT


facarroll

Recommended Posts

I have the following SELECT statement that does not show an error, but it's not working correctly, either. I suspect the CASE is not correct, but where?

 

$query = mysql_query("SELECT users.id, quiz.userId, quiz.family, quiz.quizTitle, quiz.userGroup, quiz.passState,					 
				 SUM(CASE WHEN quiz.passState=1 THEN quiz.passState * '".$pass."' ELSE (quiz.passState+1) * '".$fail."' END) AS total					 
				 FROM quiz, users 
				 WHERE  quiz.userIdRec = users.id 
				 AND quiz.addDate 
				 BETWEEN '".$start_date."' AND '".$end_date."' 
				 AND users.egroup='".$egroup5."' 
				 AND quiz.managerId='".$userid."' 
				 GROUP BY quiz.userId, quiz.quizTitle 
				 ORDER BY quiz.family, quiz.addDate") or die(mysql_error());

 

The values for the variables are dates and simple numbers. Nothing wrong with those. I suspect the syntax

 SUM(CASE WHEN quiz.passState=1 THEN quiz.passState * '".$pass."' ELSE (quiz.passState+1) * '".$fail."' END) AS total

. passState always has the value '1' or '0'. I  want to be able to derive a value from each which is a product of (in the first case) passState by the value in $pass. In the second case, I also want to calculate a value based on passState when it = '0', by simply adding '1' and multiplying by the value contained in the variable $fail.

 

Can anyone see what is wrong with the SELECT?

 

 

Link to comment
Share on other sites

I should have explained the situation better. The SELECT takes an existing student result to a quiz from the database where (passState will always equal either pass (1) or fail (0).

I want to allocate a score to each result. The score can be any value for a pass and a different value for a fail.

So passState being 1 can be multiplied by $pass to get a score.

I want to be able to give a student a mark for attempting, even though he fails,

So in this event, passState can be multiplied by $fail, but because it's value is already 0, I add 1 to passState to enable the multiplication.

I hope this is clearer.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.