当有GROUP BY时,MySQL自定义ORDER BY

时间:2015-03-25 18:57:14

标签: mysql

我想知道在我之前使用群组时如何使用自定义ORDER BY。

这是我的查询

SELECT
CASE WHEN a.edad < 40 THEN 'Menos de 40'
     WHEN a.edad >= 40 AND a.edad <=49 THEN 'De 40 a 49'
     WHEN a.edad >= 50 AND a.edad <=59 THEN 'De 50 a 59'
     WHEN a.edad >= 60 AND a.edad <=69 THEN 'De 60 a 69'
     WHEN a.edad >=70 THEN 'De 70 y más'
      ELSE(SELECT a.edad) END AS 'Grupo de edad',
      SUM(IF(a.sexo='F',1,0)) AS Mujeres,SUM(IF(a.sexo='M',1,0)) AS Hombres
FROM academicos a
WHERE CCN REGEXP 'I|D65' /*Tomando en cuenta a la persona docente*/
GROUP BY 1

结果如下:

Grupo de edad, Mujeres, Hombres
'De 40 a 49', 7, 3
'De 50 a 59', 8, 5
'De 60 a 69', 20, 25
'De 70 y más', 6, 10
'Menos de 40', 2, 0

我希望文字'Menos de 40', 2, 0显示在顶部。 我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

您必须将CASE语句复制到ORDER BY子句,并返回标准略有不同。我尽可能地将你的查询翻译成英文,我的意思是没有不尊重。

<强>查询:

SELECT 
  CASE WHEN age < 40 THEN 'Less than 40'
       WHEN age >= 40 AND age <= 49 THEN 'From 40 to 49'
       WHEN age >= 50 AND age <= 59 THEN 'From 50 to 59'
       WHEN age >= 60 AND age <= 69 THEN 'From 60 to 69'
       ELSE age END AS 'Age Grouping',
  SUM(IF(sex = 'F', 1, 0)) AS 'Girls',
  SUM(IF(sex = 'M', 1, 0)) AS 'Boys'
FROM students
GROUP BY 1
ORDER BY 
  CASE WHEN age < 40 THEN 1
       WHEN age >= 40 AND age <= 49 THEN 2
       WHEN age >= 50 AND age <= 59 THEN 3
       WHEN age >= 60 AND age <= 69 THEN 4
       ELSE 5 END

<强>结果:

+---------------+-------+------+
| Age Grouping  | Girls | Boys |
+---------------+-------+------+
| Less than 40  |     1 |    2 |
| From 40 to 49 |     0 |    1 |
| From 50 to 59 |     0 |    1 |
| From 60 to 69 |     0 |    1 |
+---------------+-------+------+

SQL Fiddle