2010-09-16 99 views
3

我有一個學生,標誌着表模式下面給出:列計數基於一系列

Student 
-------- 
SNO 
Marks 

我想產生一個結果的東西是這樣的:

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

上述結果表明,主要有:誰得到的分數爲零

  • 10名學生,
  • 2學生如何獲得1至10分,
  • 43 from 11-20
  • 等等。

任何人都可以請讓我知道如何編寫一個查詢產生這個結果?

回答

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 

OUTPUT:

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

,如果你不2005+你需要一個Numbers table更換CTE SQL Server上。並使用如下查詢:

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>[email protected] AND n.Number<[email protected] AND CONVERT(decimal(3,1),n.Number/10)=n.Number/10.0 
    GROUP BY n.number 
+0

完美。像冠軍一樣工作。非常感謝。 – Mahesh 2010-09-16 15:07:29