开发者

group range fields in mysql?

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 "a开发者_如何学编程ge" category to the ORDER BY


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


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 " ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜