返回不同的匹配和不匹配的行(外连接?)

时间:2017-06-06 00:58:52

标签: sql oracle

我知道我过去已经这样做了,现在我无法想到解决方案......我知道它是某种完全的外部联接。

我有3张桌子:

ACTIVITIES       
id   name        
---+-------------
1  |  Basketball 
2  |  Chess Club 

ENROLLMENT                   
id   activity_id   person_id 
---+-------------+-----------
1  | 1           | 1         
2  | 1           | 2         
3  | 2           | 1         

ATTENDANCE
id   date         person_id   activity_id
---+-------------+----------+---------------
1  | 2017-01-01  | 1        | 1
2  | 2017-01-01  | 2        | 1
3  | 2017-01-02  | 1        | 1

我试图通过person_id出席,即使该ID不存在日期:

date          person_id
------------+---------------
2017-01-01  | 1
2017-01-02  | null

这里有一些我认为我需要的东西......

select date, attendance.person_id
from enrollment
**SOME SORT OF JOIN** attendance on enrollment.person_id = attendance.person_id
where person_id = 1

但我能得到的只有:

date          person_id
------------+---------------
2017-01-01  | 1
2017-01-01  | 1

...行数正确但值不正确。

1 个答案:

答案 0 :(得分:1)

这似乎会产生您想要的结果:

select date,
       max(case when person_id = 1 then person_id end) as person_id
from attendance a
group by date
order by date;