2016-05-04 56 views
2

我有一張表,其中包含學校可用的類的列表。每個班級可以有多個會話。每個班級都可以分配學生。組中的不同表的COUNT個

我需要做的是獲得每個班級的所有課程數量,以及參加課程的學生人數。我已經完成了第一步,但如果我加入到學生分配表中,我的計數將會是錯誤的。

我弄明白了一些可以使用的假SQL。

我很高興從瞳孔鏈接表中獲得計數。

DECLARE @Class TABLE 
(
    ClassID INT NOT NULL, 
    ClassName VARCHAR(20) NOT NULL 
) 

INSERT INTO @Class VALUES (1, 'English') 
INSERT INTO @Class VALUES (2, 'Maths') 

DECLARE @ClassSession TABLE 
(
    ClassSessionID INT NOT NULL, 
    ClassID INT NOT NULL, 
    Description VARCHAR(100) NOT NULL 
) 

INSERT INTO @ClassSession VALUES (1, 1, 'Basic English') 
INSERT INTO @ClassSession VALUES (2, 1, 'Advanced English') 
INSERT INTO @ClassSession VALUES (3, 1, 'Amazing English') 
INSERT INTO @ClassSession VALUES (4, 2, 'Basic English') 
INSERT INTO @ClassSession VALUES (5, 2, 'Basic English') 

DECLARE @ClassPupil TABLE 
(
    ClassPupilID INT NOT NULL, 
    ClassID INT NOT NULL, 
    PupilID INT NOT NULL -- FK to the Pupils table. 
) 

INSERT INTO @ClassPupil VALUES (1, 1, 1000) 
INSERT INTO @ClassPupil VALUES (2, 1, 1001) 
INSERT INTO @ClassPupil VALUES (3, 1, 1002) 
INSERT INTO @ClassPupil VALUES (4, 1, 1003) 
INSERT INTO @ClassPupil VALUES (5, 1, 1004) 

INSERT INTO @ClassPupil VALUES (6, 2, 1005) 
INSERT INTO @ClassPupil VALUES (7, 2, 1006) 
INSERT INTO @ClassPupil VALUES (8, 2, 1007) 


SELECT ClassName, COUNT(*) AS Sessions, '??' AS NumerOfPupils 
FROM @Class c 
INNER JOIN @ClassSession cs 
ON cs.ClassID = c.ClassID 
GROUP BY c.ClassID, c.ClassName 

它也許可以用子查詢來完成?這是最好的方法嗎?

回答

2

對於每個班級,您有兩個獨立的維度。您需要單獨骨料他們:

SELECT c.ClassName, cs.Sessions, cp.Pupils 
FROM @Class c INNER JOIN 
    (SELECT ClassId, COUNT(*) as sessions 
     FROM @ClassSession cs 
     GROUP BY ClassId 
    ) cs 
    ON cs.ClassID = c.ClassID INNER JOIN 
    (SELECT ClassId, COUNT(*) as pupils 
     FROM @ClassPupil cp 
     GROUP BY ClassId 
    ) cp 
    ON cp.ClassId = c.ClassId; 
2

另一種方法是使用CROSS APPLY讓學生們的計數:

SELECT 
    ClassName, COUNT(*) AS Sessions, cp.NumberOfPupils 
FROM @Class c 
INNER JOIN @ClassSession cs 
    ON cs.ClassID = c.ClassID 
CROSS APPLY (
    SELECT COUNT(*) AS NumberOfPupils 
    FROM @ClassPupil 
    WHERE 
     ClassID = c.ClassID 
) cp 
GROUP BY c.ClassID, c.ClassName, cp.NumberOfPupils 
0
SELECT ClassName, COUNT(distinct cs.ClassSessionID) AS Sessions, /*'??'*/ count(distinct cp.PupilID) AS NumerOfPupils 
FROM @Class c 
INNER JOIN @ClassSession cs 
ON cs.ClassID = c.ClassID 
inner join @ClassPupil cp on c.ClassID=cp.ClassID 
GROUP BY /*c.ClassID,*/ c.ClassName 

計數(不同的...)解決了(工作周圍)問題。
一般來說,這是(A - > B,C)的問題。

相關問題