如何在查询中按计算列分组?

rqenqsqc  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(394)

我想用 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

等。

tcbh2hod

tcbh2hod1#

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

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
vecaoik1

vecaoik12#

你可以简单地使用相同的 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

相关问题