加入3个表

时间:2016-07-27 21:38:11

标签: sql db2

我有3个表STUDENT,STUDENT_GPA,STUDENT_ATTENDANCE如下

STUDENT
--------
STUDENT_ID STUDENT_NAME
-----------------------
1          A
2          B
3          C
4          D
5          E

SUBJECTS
--------
STUDENT_ID  GPA UPDATE_FLG
---------------------------
2           8     Y
4           7     Y
5           8     N


STUDENT_ATTENDANCE
------------------
STUDENT_ID  ATTENDANCE  UPDATE_FLG
----------------------------------
3           92           Y


Output should be

STUDENT_ID STUDENT_NAME GPA    ATTENDANCE
--------------------------------------
2           B           8      NULL
3           C           NULL   92
4           D           7      NULL

我尝试了以下查询,但它无法正常工作。它缺少来自任何一个表的行

SELECT S.STUDENT_ID,
       S.STUDENT_NAME,
       SD.GPA,
       SA.ATTENDANCE
FROM STUDENT S
LEFT OUTER JOIN STUDENT_GPA SD ON (S.STUDENT_ID=SD.STUDENT_ID
                                   AND SD.UPDATE_FLG='Y')
LEFT OUTER JOIN STUDENT_ATTENDANCE SA ON (S.STUDENT_ID=SA.STUDENT_ID
                                          AND SA.UPDATE_FLG='Y')

请帮忙!感谢

3 个答案:

答案 0 :(得分:1)

虽然,您的问题不清楚您需要什么样的结果集,但是,看起来您想为那些GPA更新或考勤更新且您想忽略所有其他记录的学生选择数据

基于这种理解,下面的查询为您提供了预期的结果集。

SELECT S.STUDENT_ID, S.STUDENT_NAME, SD.GPA, SA.ATTENDANCE 
FROM STUDENT S LEFT OUTER JOIN STUDENT_GPA SD ON 
(S.STUDENT_ID=SD.STUDENT_ID)
LEFT OUTER JOIN STUDENT_ATTENDANCE SA ON (S.STUDENT_ID=SA.STUDENT_ID)
WHERE SA.UPDATE_FLG = 'Y' OR SD.UPDATE_FLG = 'Y'

答案 1 :(得分:0)

Function MonthEnd(d)
    Dim actualmonthend, dow, ans
    actualmonthend = DateSerial(Year(d), Month(d) + 1, 1) - 1
    dow = Weekday(actualmonthend)
    If (dow < 4) Then
        ans = actualmonthend - dow
    Else
        ans = actualmonthend + (7 - dow)
    End If
    MonthEnd = ans
End Function

答案 2 :(得分:0)

以下是使用conditional aggregation的一个选项:

select *
from (
  select s.student_id, s.student_name,
    max(case when sub.update_flag = 'Y' then sub.gpa end) gpa,
    max(case when att.update_flag = 'Y' then att.attendance end) attendance
  from student s 
    left join subjects sub on s.student_id = sub.student_id 
    left join student_attendance att on s.student_id = att.student_id
  group by s.student_id, s.student_name
  ) t
where gpa is not null or attendance is not null