2012-03-11 63 views
0

早上好。Transact SQL在每個組中查找最大註冊數

我有一個表結構(我用SQL SERVER 2000)

CourseID StudentName TermPaperID

101   Jon   1 
101   Jon   2 
101   Jon   3 
101   David   1 
101   David   2 
102   David   5 
102   David   6 
102   George   5 

我想列出CourseID,StudentName,每場最多註冊。

我嘗試以下查詢

select 
CourseId, 
StudentName, 
max(x.numberofregistration) as max_registration 
from 
(
    select 
      CourseID, 
      StudentName, 
      count(CourseID) as numberofregistration 
    from 
    dbo.Students 
      group by CourseId,StudentName 
)x 
group by CourseId,StudentName 

,但它並沒有得到預期的結果。

預期的結果是 我有一個表結構

CourseID StudentName max_registration

101   Jon   3 
102   David   2 

如何實現預期的結果?提前致謝。

+0

SQL Server 2000?我爲你感到難過,但爲什麼? – 2012-03-11 17:03:36

+0

如果還有另一行:「102,George,5」你會如何期待這會影響結果? – ninesided 2012-03-11 23:10:33

回答

1

這是一個非常非常醜陋的方式。我想我寧願花費升級費用,也不願寫太多這樣的東西。希望別人能拿出更乾淨的東西。

CREATE TABLE #x(CourseID INT, StudentName VARCHAR(32), TermPaperID INT); 

INSERT #x SELECT 101,'Jon ',1; 
INSERT #x SELECT 101,'Jon ',2; 
INSERT #x SELECT 101,'Jon ',3; 
INSERT #x SELECT 101,'David ',1; 
INSERT #x SELECT 101,'David ',2; 
INSERT #x SELECT 102,'David ',5; 
INSERT #x SELECT 102,'David ',6; 
INSERT #x SELECT 102,'George',5; 

SELECT b.CourseID, b.StudentName, max_registration = COUNT(*) 
FROM #x AS b 
INNER JOIN (
    SELECT CourseID, c = MAX(c) 
    FROM 
    (
    SELECT CourseID, StudentName, c = COUNT(CourseID) 
    FROM #x GROUP BY CourseID, StudentName 
) AS x GROUP BY CourseID 
) AS s 
ON b.CourseID = s.CourseID 
GROUP BY b.CourseID, b.StudentName 
HAVING COUNT(*) = MAX(s.c) 
ORDER BY b.CourseID; 
+0

非常感謝您花時間引導我。我同意使用row_number()和Partition我們可以很容易地解決這個問題,但我正在處理客戶端項目,他們仍然使用SQL Server 2000。 – user1256813 2012-03-11 17:40:46

0

看來您的CTE'x'按照您計算的值進行分組。簡單地計算一個不同的領域(即術語論文ID)應該提供預期的結果。

這就是說,在你想要的結果樣本中,我不清楚爲什麼這些結果是預期的樣本數據。如果我誤解了這個問題,我很樂意再次嘗試! :-)