2009-11-12 3 views
0

코스 (PK 코스 ID, 제목) 및 참석자 (PK 참석자 ID, FK 코스 ID, 방법)의 두 테이블이 있습니다.
많은 참석자가 6 가지 방법 중 하나를 통해 주어진 코스를 택할 수 있습니다.SQL Server 2005에서 통계 모드 계산

코스 테이블 (CourseId, Title)의 각 코스 당 하나의 레코드를 각 코스의 모든 참석자를위한 Method의 통계 모드로 어떻게 인쇄 할 수 있습니까?

+1

간다. –

답변

2

나는 당신이 필요로하는 것을 이해합니다. 이 Mode (statistics) 가입일

,

모드는 동일한 최대 주파수를 다른 값으로 얻어 질 수 있으므로 , 반드시 고유하지 않다.

그래서 여기에 예를 들어 당신이 필요로하는 출력 데이터를 제공

DECLARE @Course TABLE(
     CourseID INT, 
     Title VARCHAR(50) 
) 

INSERT INTO @Course (CourseID,Title) SELECT 1, 'AA' 
INSERT INTO @Course (CourseID,Title) SELECT 2, 'BB' 
INSERT INTO @Course (CourseID,Title) SELECT 3, 'CC' 

DECLARE @Attendee TABLE(
     AttendeeID INT, 
     CourseID INT, 
     Method INT 
) 

INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 1, 1, 1 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 2, 1, 1 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 3, 1, 2 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 4, 1, 1 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 5, 1, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 6, 1, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 7, 1, 4 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 8, 1, 4 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 9, 1, 5 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 10, 1, 6 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 11, 1, 6 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 12, 1, 6 

INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 13, 2, 1 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 14, 2, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 15, 2, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 16, 2, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 17, 2, 3 
INSERT INTO @Attendee (AttendeeID,CourseID,Method) SELECT 18, 2, 6 

DECLARE @Counts TABLE(
     CourseID INT, 
     Title VARCHAR(50), 
     Method INT, 
     NumberMethodPerCourse INT 
) 

INSERT INTO @Counts (CourseID,Title,Method,NumberMethodPerCourse) 
SELECT c.CourseID, 
     c.Title, 
     a.Method, 
     COUNT(a.Method) NumberMethodPerCourse 
FROM @Course c INNER JOIN 
     @Attendee a ON c.CourseID = a.CourseID 
GROUP BY c.CourseID, 
      c.Title, 
      a.Method 

SELECT CourseMax.CourseID, 
     CourseMax.Title, 
     CourseMax.MaxNumber, 
     Counts.Method 
FROM (
      SELECT Counts.CourseID, 
        Counts.Title, 
        MAX(NumberMethodPerCourse) MaxNumber 
      FROM @Counts Counts 
      GROUP BY Counts.CourseID, 
         Counts.Title 
     ) CourseMax INNER JOIN 
     @Counts Counts ON CourseMax.CourseID = Counts.CourseID 
         AND CourseMax.MaxNumber = Counts.NumberMethodPerCourse 
+0

완벽한! 내가 필요한 것. 그냥 내 요구에 대한 여분의 WHERE 절을 던져서 나는 좋은거야. 나는 하나의 쿼리에서 테이블을 사용하지 않으려 고 노력했다. 감사. – DancesWithBamboo

+0

테이블 없이도 할 수 있지만 엉망이됩니다. X-) –

관련 문제