SQL

在SQL中,如何对范围进行“分组依据”?

发布于 2021-04-20 22:56:22

假设我有一个带有数字列的表(我们称其为“分数”)。

我想生成一个计数表,该表显示每个范围内得分出现的次数。

例如:

score range  | number of occurrences
-------------------------------------
   0-9       |        11
  10-19      |        14
  20-29      |         3
   ...       |       ...

在此示例中,分数在0到9之间的行有11行,分数在10到19之间的行有14行,分数在20-29范围内的行有3行。

有一个简单的方法来设置它吗?您有什么推荐的吗?

关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-04-20
    为面试而生,有面试问题,就找面试哥。

    在SQL Server 2000上,投票率最高的答案均不正确。也许它们使用的是其他版本。

    这是它们在SQL Server 2000上的正确版本。

    select t.range as [score range], count(*) as [number of occurences]
    from (
      select case  
        when score between 0 and 9 then ' 0- 9'
        when score between 10 and 19 then '10-19'
        else '20-99' end as range
      from scores) t
    group by t.range
    

    或者

    select t.range as [score range], count(*) as [number of occurrences]
    from (
          select user_id,
             case when score >= 0 and score< 10 then '0-9'
             when score >= 10 and score< 20 then '10-19'
             else '20-99' end as range
         from scores) t
    group by t.range
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看