如何对查询中的计算列进行分组?

时间:2018-07-26 12:15:38

标签: mysql group-by mariadb

我正在尝试使用Case when语句根据条件标记数据。然后,我需要对类别进行分组,以便能够对它们进行计数。我无法使用临时表执行此任务。

SELECT player_name,
       weight,
       CASE WHEN weight > 250 THEN 'over 250'
            WHEN weight > 200 AND weight <= 250 THEN '201-250'
            WHEN weight > 175 AND weight <= 200 THEN '176-200'
            ELSE '175 or under' END AS weight_group
  FROM benn.college_football_players

输出:

Over 250    10
201-250     50
176-200     3

2 个答案:

答案 0 :(得分:0)

您可以将派生表(子选择)用于组,例如:

  select  t.weight_group, count(*) from (
    SELECT player_name,
           weight,
           CASE WHEN weight > 250 THEN 'over 250'
                WHEN weight > 200 AND weight <= 250 THEN '201-250'
                WHEN weight > 175 AND weight <= 200 THEN '176-200'
                ELSE '175 or under' END AS weight_group
      FROM benn.college_football_players

  ) t 
  group by weight_group 

答案 1 :(得分:0)

您可以在case子句中使用相同的group by表达式:

SELECT CASE WHEN weight > 250 THEN 'over 250'
            WHEN weight > 200 AND weight <= 250 THEN '201-250'
            WHEN weight > 175 AND weight <= 200 THEN '176-200'
            ELSE '175 or under' END AS weight_group,
       COUNT(*)
FROM benn.college_football_players
GROUP BY CASE WHEN weight > 250 THEN 'over 250'
            WHEN weight > 200 AND weight <= 250 THEN '201-250'
            WHEN weight > 175 AND weight <= 200 THEN '176-200'
            ELSE '175 or under' END