tags:

views:

17

answers:

2

Is it possible to adapt this mysql statement:

$sql = "SELECT u.user_registered, 
               u.first,
               u.last,
               c.class_grade 
        FROM users u 
        JOIN classes c on 
           c.class_id  = u.class_id and
        WHERE user_registered >=  '".  $from  . "' 
          and user_registered <  '".  $to  . "' 
        ORDER by u.last " ;

I want to group grades into an age category: 'young' and 'old'

if c.class_grade = 1,2, or 3, then age = 'young' if c.class_grade = 4,5, or 6, then age = 'old'

Finally add this new "age" category to the ORDER BY

A: 
SELECT u.user_registered, 
               u.first,
               u.last,
               c.class_grade,
               CASE WHEN c.class_grade IN (1,2,3) THEN 'young' WHEN c.class_grade IN (4,5,6) THEN 'old' END AS 'Age'
        FROM users u 
        JOIN classes c on 
           c.class_id  = u.class_id and
        WHERE user_registered >=  '".  $from  . "' 
          and user_registered <  '".  $to  . "' 
        ORDER by u.last,
               CASE WHEN c.class_grade IN (1,2,3) THEN 'young' WHEN c.class_grade IN (4,5,6) THEN 'old' END
flayto
A: 

You can try this:

$sql = "SELECT u.user_registered, 
           u.first,
           u.last,
           c.class_grade,
           IF(c.class_grade IN (1, 2, 3), 'young', 'old') AS age
    FROM users u 
    JOIN classes c on 
       c.class_id  = u.class_id and
    WHERE user_registered >=  '".  $from  . "' 
      and user_registered <  '".  $to  . "' 
    ORDER by u.last, age " ;
WoLpH
it works like a charm!!
roger rover