2016-04-21 185 views
0

我有學生和評估表。有必要返回所有評級的重複次數,但不包括MIN和MAX重複次數。SQL有聚合函數嗎?

當我'運行過程中出現此查詢:

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

我有這樣的結果,它是好的,但如何顯示此查詢withuout重複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) 

非常感謝。

+0

您使用的數據庫是? –

+0

MS SQL Server 2012 – enzodev

回答

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關鍵字只能使用一次。

+0

非常感謝。它工作.. :-) – enzodev

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 
+0

謝謝..工作 – enzodev

+1

你應該給一個複選標記答案。我不在乎你是否給了戈登答案。 – Paparazzi

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) 
) 

這裏我們使用公共表表達式的概念,它類似於子查詢。

+0

謝謝你的工作。 – enzodev

+0

酷!很高興它有幫助。 :) –

0

我這樣解決了這個問題,但是CTE就是很好的例子。感謝大家。

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)