列数基于范围

时间:2010-09-16 14:51:02

标签: sql-server tsql count

我有一个带有模式的学生标记表,如下所示:

Student
--------
SNO
Marks

我希望产生一个结果:

MarksRange   Count
----------   ------
0             10
10             2
20             43
:              :
100            2

以上结果显示:

  • 10名得分为零的学生,
  • 2名学生如何得分在1到10之间,
  • 43 from 11-20
  • 等等。

有谁能告诉我如何编写产生此结果的查询?

1 个答案:

答案 0 :(得分:5)

试试这个:

DECLARE @Student table (SNO int,Marks int)

INSERT INTO @Student VALUES (1, 0)
INSERT INTO @Student VALUES (1, 3)
INSERT INTO @Student VALUES (1, 45)
INSERT INTO @Student VALUES (1, 95)
INSERT INTO @Student VALUES (1, 85)
INSERT INTO @Student VALUES (1, 97)
INSERT INTO @Student VALUES (1, 92)

DECLARE @StartNumber int
       ,@EndNumber   int
SELECT @StartNumber=0
      ,@EndNumber=100

;WITH AllNumbers AS
(
    SELECT @StartNumber AS Number
    UNION ALL
    SELECT Number+10
        FROM AllNumbers
        WHERE Number<@EndNumber
)
SELECT
    n.number AS MarksRange,COUNT(s.SNO) AS CountOf
    FROM AllNumbers               n
        LEFT OUTER JOIN @Student  s ON s.Marks=n.Number OR (s.Marks>n.Number-10 AND s.Marks<=n.Number)
    GROUP BY n.number

输出:

MarksRange  CountOf
----------- -----------
0           1
10          1
20          0
30          0
40          0
50          1
60          0
70          0
80          0
90          1
100         3

如果您不在SQL Server 2005+上,则需要使用Numbers table替换CTE。并使用如下查询:

SELECT
    n.number,COUNT(s.SNO),0 AS CountOf
    FROM Numbers                  n
        LEFT OUTER JOIN @Student  s ON s.Marks=n.Number OR (s.Marks>n.Number-10 AND s.Marks<=n.Number)
    WHERE n.Number>=@StartNumber AND n.Number<=@EndNumber AND CONVERT(decimal(3,1),n.Number/10)=n.Number/10.0
    GROUP BY n.number