SQL Server - 如何只在select之间的其他属性时加入

时间:2014-05-27 21:58:16

标签: sql sql-server

我正在尝试查询以显示学生的出勤记录。这些是我的表。

enter image description here

这是我到目前为止开始的......

我正在将studentId(StudentCalendar)列表与学校开放日期(DateCollection)匹配,然后记录错过的天数(出勤率)。

我最终得到这样的东西..

 SELECT s.personid,
        dc.calendarid, 
        dc.[date], 
        coalesce(absentMinutes,0) AS absentMinutes
   FROM [dbo].[StudentCalendar] s
        INNER JOIN [dbo].[DateCollection] dc ON s.calendarId = dc.calendarId
         LEFT JOIN [dbo].[Attendance] a ON a.dateOccurred = dc.[date]
               AND a.personId = s.personId

enter image description here

我现在有一份学生名单,每天都有学校开放。 我的问题是并非每个学生都注册了整个学年。

我是否有办法只将学生列表(StudentCalendar)与学校开放日期(DateCollection)匹配,当它在学生日历startDate& amp;每个学生的endDate(日历)?

像这样......

enter image description here

2 个答案:

答案 0 :(得分:2)

这应该适合你:

SELECT s.personid,
    dc.calendarid, 
    dc.[date], 
    coalesce(absentMinutes,0) AS absentMinutes
FROM [dbo].[StudentCalendar] s
    INNER JOIN [dbo].[DateCollection] dc ON s.calendarId = dc.calendarId
    INNER JOIN [dbo].[Attendance] a ON a.dateOccurred = dc.[date]
           AND a.personId = s.personId
           AND dc.[date] BETWEEN s.startDate AND isnull(s.endDate,'99991231')

答案 1 :(得分:0)

在Frazz的帮助下。我好像找到了答案..

我在JOIN ON子句中添加了附加条件以及在endDate中处理NULL值的CASE语句

SELECT s.personid,
        dc.calendarid, 
        dc.[date],
        COALESCE(absentMinutes,0) AS absentMinutes
  FROM [dbo].[StudentCalendar] s 
            LEFT JOIN [dbo].[DateCollection] dc ON s.calendarId=dc.calendarId 
                AND dc.[date] >= s.startDate 
                AND dc.[date] <= (CASE 
                                        WHEN s.endDate is null 
                                        THEN (SELECT c.endDate FROM Calendar c WHERE c.calendarId=s.calendarId) 
                                        ELSE s.endDate 
                                  END)
            LEFT JOIN [dbo].[Attendance] a ON a.dateOccurred=dc.[date] AND a.personId=s.personId

或者,这也适用。

SELECT s.personid,
        dc.calendarid, 
        dc.[date],
        COALESCE(absentMinutes,0) AS absentMinutes, 
  FROM [dbo].[StudentCalendar] s 
            LEFT JOIN [dbo].[DateCollection] dc 
                ON s.calendarId=dc.calendarId AND dc.[date] BETWEEN s.startDate AND ISNULL(s.endDate,'99991231')
            LEFT JOIN [dbo].[Attendance] a 
                ON a.dateOccurred=dc.[date] AND a.personId=s.personId