sql server 2012中的复杂子查询

时间:2014-03-29 11:30:15

标签: sql sql-server tsql sql-server-2012

我有两张桌子  1 attend_master包含

AM_ID Attend_Date Time_From Time_To Course_ID Subject_ID
 1     2014-03-10  10:00     11:00    1        22
 2     2014-03-10  10:00     11:00    1        23

第二次Attend_Child

CA_ID   AM_ID   Roll_No  Attendance
1           1       1         1
2           1       2         0
3           1       3         1
4           2       1         1

我想要这样的结果

Subject_ID    Total_Absenty   Total_Lectures
22             2                10
23             5                11

我试过了

select AM.Subject_ID, count(AC.Attendance) as Attendance
,
(
    select count(AC1.Attendance) from Attend_Child AC1
    inner join Attend_Master AM1 on AC1.TT_ID = AM1.TT_ID
    where AC1.Roll_No = 3 AND AM1.Course_ID = 1 AND DATENAME(Month, AM1.Attend_Date) = 'March'
)
 from Attend_Child AC
inner join Attend_Master AM on AC.TT_ID = AM.TT_ID
where AC.Roll_No = 3 AND AM.Course_ID = 1 AND AC.Attendance = 0 AND DATENAME(Month, AM.Attend_Date) = 'March'
group by AM.Subject_ID, AM.subject_Type

通过使用这个我得到不正确的结果。 如何在子查询中使用group by?

1 个答案:

答案 0 :(得分:0)

DECLARE @CourseID INT =1
DECLARE @Month varchar(10)='March'

SELECT m.SubjectID
    ,Count(*) [Lectures] --count of all classes attended or not
    ,Count(*)-SUM(c.Attendance) [Absences]--count of all - attended classes
FROM Attend_Master m
INNER JOIN Attend_Child c
    ON m.AM_ID=c.AM_ID  --WHAT IS TT_ID?
WHERE m.CourseID=@CourseID
    DATENAME(Month, m.Attend_Date) = @Month
    --AC.Roll_No = 3  --WHAT DOES THIS DO FOR YOU?
GROUP BY M.Subject_ID
--, AM.subject_Type  --WHERE DID THIS COME FROM?