ORDER BY与CASE MySQL

我有一个“积分榜”查询,它显示了我所在的联赛的统计数据.我试图根据一些条件订购查询.

>如果团队在积分中排名1-25,则按胜利,积分排序
>如果球队排名在前25名之外(第26位至第42位),请按分数排序.

我能描述它的最好方法是,它应该像两个表一样.排名(1-25)的队伍应该排在一起,排名(26-42)的队伍应该排在一起.

这是我的查询.

SELECT m.Team AS team
, SUM( r.points ) AS points
, SUM(CASE
    WHEN rank = 1 THEN 1
    ELSE 0
  END) AS Wins
, SUM(CASE
    WHEN rank < 6 THEN 1
    ELSE 0
  END) AS T5
, SUM(CASE
    WHEN rank < 11 THEN 1
    ELSE 0
  END) AS T10
, SUM(CASE
    WHEN rank < 21 THEN 1
    ELSE 0
  END) AS T20
, ROUND(Avg(r.points),2) AS ppr
, ROUND(Avg(r.rank),2) as avg_finish
, MIN(r.rank) as best
FROM members m
LEFT JOIN results r ON r.team_id = m.M_ID
GROUP BY team
ORDER BY 
    CASE
        WHEN COUNT(*) < 26
        THEN Wins 
        WHEN COUNT(*) > 25
        THEN points
    END DESC, points DESC;

由于我的别名“Wins”,我收到错误“Reference’Wins’不支持(引用组功能).相反,我尝试过:

ORDER BY 
    CASE
        WHEN COUNT(*) < 26
        THEN SUM(CASE
            WHEN rank = 1 THEN 1
            ELSE 0
        END)  
        WHEN COUNT(*) > 25
        THEN points
    END DESC, points DESC;

这成功地命令我的表,但不考虑COUNT(*)> 25 CASE条款,只是按顺序,然后点.关于如何重构ORDER BY子句的任何想法?

最佳答案 您应该在外部查询中执行该ORDER BY,因为在ORDER子句中无法访问列别名Wins.

SELECT * FROM (
SELECT m.Team AS team
, SUM( r.points ) AS points
, SUM(CASE
    WHEN rank = 1 THEN 1
    ELSE 0
  END) AS Wins
, SUM(CASE
    WHEN rank < 6 THEN 1
    ELSE 0
  END) AS T5
, SUM(CASE
    WHEN rank < 11 THEN 1
    ELSE 0
  END) AS T10
, SUM(CASE
    WHEN rank < 21 THEN 1
    ELSE 0
  END) AS T20
, ROUND(Avg(r.points),2) AS ppr
, ROUND(Avg(r.rank),2) as avg_finish
, MIN(r.rank) as best
FROM members m
LEFT JOIN results r ON r.team_id = m.M_ID
GROUP BY team ) XXX
ORDER BY 
    CASE
        WHEN COUNT(*) < 26
        THEN Wins 
        WHEN COUNT(*) > 25
        THEN points
    END DESC, points DESC;
点赞