SQL有聚合函数吗?

时间:2016-04-21 20:36:18

标签: sql sql-server max min having

我有学生和评估表。有必要返回所有评级的重复次数,但没有MIN和MAX重复次数等级。

当我跑这个查询时:

SELECT 
     [Grade],
     COUNT([Grade]) AS [Number of repetitions]
     FROM [Test].[dbo].[Evaluation]
     GROUP BY Grade 

我有这个结果,没关系,但如何用MIN和MAX重复次数显示这个查询。(在这种情况下6 - 120和10 - 4)

Grade    Number of repetitions
 6              120
 7              35
 8              93
 9              25
10              4 

我尝试过以这种方式,但它不起作用。这是SQL中的消息:“无法对包含聚合或子查询的表达式执行聚合函数”

SELECT 
     [Grade],
     COUNT([Grade]) AS [Number of repetitions]
     FROM [Test].[dbo].[Evaluation]
     GROUP BY Grade 
     HAVING COUNT([Grade) > (SELECT MIN(COUNT([Grade])) FROM [Test][dbo].[Evaluation] GROUP BY Grade) 
     AND 
     HAVING COUNT([Grade) < (SELECT MAX(COUNT([Grade])) FROM [Test][dbo].[Evaluation] GROUP BY Grade)

非常感谢。

4 个答案:

答案 0 :(得分:1)

您不能嵌套这样的聚合函数。您可以使用许多方法来解决此问题。在您的情况下,您可以使用TOPORDER BY

获取极值
 HAVING COUNT([Grade) > (SELECT TOP 1 COUNT([Grade]) FROM [Test].[dbo].[Evaluation] GROUP BY Grade ORDER BY COUNT([Grade]) ASC ) AND
        COUNT([Grade) < (SELECT TOP 1 COUNT([Grade]) FROM [Test].[dbo].[Evaluation] GROUP BY Grade ORDER BY COUNT([Grade]) DESC)

此外,HAVING关键字仅使用一次。

答案 1 :(得分:1)

select TT.* 
FROM ( SELECT [Grade] 
            , COUNT([Grade]) AS [Number of repetitions]
            , ROW_NUMBER OVER (ORDER BY COUNT([Grade]) desc) rnD 
            , ROW_NUMBER OVER (ORDER BY COUNT([Grade]) asc)  rnA
         FROM [Test].[dbo].[Evaluation]
        GROUP BY Grade 
     ) TT
WHERE  TT.rnD <> 1 AND TT.rnA <> 1

答案 2 :(得分:0)

WITH Fact As
(
SELECT 
     [Grade],
     COUNT([Grade]) AS [Number of repetitions]
     FROM [Test].[dbo].[Evaluation]
     GROUP BY Grade
)

SELECT Grade, [Number of repetitions] FROM Fact 
WHERE 
[Number of repetitions] NOT IN
(
(SELECT MAX([Number of repetitions]) FROM Fact), 
(SELECT MIN([Number of repetitions]) FROM Fact)
)

这里我们使用公共表表达式的概念,它类似于子查询。

答案 3 :(得分:0)

我通过这种方式解决了这个问题,但是CTE就是很好的例子。谢谢大家。

cmake