在SQL Server 2005中计算统计模式

时间:2009-11-12 06:46:24

标签: sql-server-2005

我有这两个表:课程(PK CourseId,Title)和参加者(PK AttendeeId,FK CourseId,Method)。
许多与会者可以通过6种方法中的任何一种来参加特定课程。

如何使用Method的统计模式为每个课程的所有与会者打印课程表(CourseId,Title)中每门课程的一条记录?

1 个答案:

答案 0 :(得分: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