我有這兩個表:課程(PK CourseId,Title)和參加者(PK AttendeeId,FK CourseId,方法)。
許多與會者可以通過6種方法中的任何一種來進行給定的課程。計算SQL Server 2005中的統計模式
如何在課程表(CourseId,Title)中爲每個課程的所有參加者使用Method的統計模式打印出每個課程的一條記錄?
我有這兩個表:課程(PK CourseId,Title)和參加者(PK AttendeeId,FK CourseId,方法)。
許多與會者可以通過6種方法中的任何一種來進行給定的課程。計算SQL Server 2005中的統計模式
如何在課程表(CourseId,Title)中爲每個課程的所有參加者使用Method的統計模式打印出每個課程的一條記錄?
好的,根據我的理解你需要。
模式不一定是唯一的,因爲 相同的最大頻率可以 爲不同的值來實現。
所以這裏去
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
完美!正是我需要的。只是爲了滿足我的需要而在附加的條款中加入了我很高興。我試圖在沒有表的一個查詢中執行它(不太好)。謝謝。 – DancesWithBamboo 2009-11-12 07:57:19
您可以在沒有桌子的情況下做到這一點,但它會變得雜亂無章) – 2009-11-12 07:58:32
給例子中,你需要輸出的數據。 – 2009-11-12 07:03:08