我无法排序(升序/降序)MySql查询的这一部分?

时间:2012-11-29 05:29:43

标签: mysql

我想对这些元素进行升序/降序排序。

查询的一部分:

sum(CASE WHEN a.question_id=39 AND u.answer_id =215 THEN 1 ELSE 0 END) as optcount1,
sum(CASE WHEN a.question_id=39 AND u.answer_id =216 THEN 1 ELSE 0 END) as optcount2,
sum(CASE WHEN a.question_id=39 AND u.answer_id =217 THEN 1 ELSE 0 END) as optcount3,
sum(CASE WHEN a.question_id=39 AND u.answer_id =218 THEN 1 ELSE 0 END) as optcount4,

完整查询:

 SELECT 39 AS ques_id,215 as optid1,216 as optid2,217 as optid3,218 as optid4, 
'Easy to start the business' as optans1,
'Lower tax rate than a corporation' as optans2,
'Liability is shared' as optans3,
'Owner has total control and say over business' as optans4, 
sum(CASE WHEN a.question_id=39 AND u.answer_id =215 THEN 1 ELSE 0 END) as optcount1,
sum(CASE WHEN a.question_id=39 AND u.answer_id =216 THEN 1 ELSE 0 END) as optcount2,
sum(CASE WHEN a.question_id=39 AND u.answer_id =217 THEN 1 ELSE 0 END) as optcount3,
sum(CASE WHEN a.question_id=39 AND u.answer_id =218 THEN 1 ELSE 0 END) as optcount4, 
'217' as answer, 4 as count FROM `user_training_answers_statistics` as u,
answers as a WHERE a.question_id='39' AND u.answer_id=a.answer_id

任何人请给我解决方案..

1 个答案:

答案 0 :(得分:0)

将其包装在另一个查询中,然后进行排序:

  select * from
    (SELECT 39 AS ques_id,215 as optid1,216 as optid2,217 as optid3,
            218 as optid4, 'Easy to start the business' as optans1,
            'Lower tax rate than a corporation' as optans2,
            'Liability is shared' as optans3,
            'Owner has total control and say over business' as optans4, 
            sum(CASE WHEN a.question_id=39 AND u.answer_id =215 THEN 1 ELSE 0 END) 
            as optcount1,
            sum(CASE WHEN a.question_id=39 AND u.answer_id =216 THEN 1 ELSE 0 END) 
            as optcount2,
            sum(CASE WHEN a.question_id=39 AND u.answer_id =217 THEN 1 ELSE 0 END) 
           as optcount3,
           sum(CASE WHEN a.question_id=39 AND u.answer_id =218 THEN 1 ELSE 0 END) 
           as optcount4, '217' as answer, 4 as count 
     FROM user_training_answers_statistics as u,
          answers as a
     WHERE a.question_id='39' AND u.answer_id=a.answer_id) as tmpTable
 ORDER BY optcount1, optcount2, optcount3, optcount4 ASC;