[英]Oracle Query with multiple records
我的學生表有多個列,但是,我只對重新注冊列和exitcode列感興趣。 當學生畢業時,他們的代碼為“ W21”,當他們升入下一年級時,他們的代碼為“ P”。 他們還將在重新注冊列中包含包含注冊日期的相應記錄。
我需要找到所有退出代碼為“ W21”並且過去四年也一直在學區學習的學生。 因此,代碼為“ W21”且僅在本學區呆了3年的學生不會被拉走。
Lisa, Simpson 240011111111 20-AUG-07 W10
Lisa, Simpson 240011111111 18-AUG-08 W10
Lisa, Simpson 240011111111 18-AUG-09 W21
Bart, Simpson 240022222222 07-AUG-00 W10
Bart, Simpson 240022222222 09-AUG-01 W10
Bart, Simpson 240022222222 08-AUG-02 W10
Bart, Simpson 240022222222 11-AUG-03 W10
Bart, Simpson 240022222222 09-AUG-04 W10
Bart, Simpson 240022222222 08-AUG-05 W10
Bart, Simpson 240022222222 14-AUG-06 W10
Bart, Simpson 240022222222 20-AUG-07 W10
Bart, Simpson 240022222222 18-AUG-08 W10
Bart, Simpson 240022222222 18-AUG-09 W21
Homer, Simpson 240000333333 07-AUG-00 W10
Homer, Simpson 240000333333 09-AUG-01 W10
Homer, Simpson 240000333333 08-AUG-02 W10
Homer, Simpson 240000333333 11-AUG-03 W10
Homer, Simpson 240000333333 09-AUG-04 W10
Homer, Simpson 240000333333 08-AUG-05 W10
Homer, Simpson 240000333333 14-AUG-06 W10
Homer, Simpson 240000333333 20-AUG-07 W10
Homer, Simpson 240000333333 18-AUG-08 W10
Homer, Simpson 240000333333 18-AUG-09 NS
Homer, Simpson 240000333333 21-AUG-09 W21
基本上,我只需要拉Bart和Homer,因為他們畢業前的四年在該地區。 麗莎不會被拉。
我為如何做到這一點感到煩惱,任何幫助都會很棒。
謝謝
這樣的事情不會很快,但是會起作用:
select *
from studentrecords
where exitcode = 'W21'
and studentid in (select studentid
from studentrecords
where exitcode = 'W21'
intersect
select studentid
from studentrecords
where enrollmentyear >= :fouryearsago
group by studentid
having count (*) >= 4)
具有having子句的group by應該足夠了。 截斷日期到年份並計算不重復數應該可以解決年數。
select
e.student, e.sid, count(distinct trunc(dated,'YYYY')) num_years
from enrollments e
inner join (select distinct sid from enrollments where exitcode = 'W21' ) x on e.sid = x.sid
group by e.student, e.sid
having count(distinct trunc(dated,'YYYY')) > 3
+----+---------------+--------------+-----------+
| | STUDENT | SID | NUM_YEARS |
+----+---------------+--------------+-----------+
| 1 | Bart,Simpson | 240022222222 | 10 |
| 2 | Homer,Simpson | 240000333333 | 10 |
+----+---------------+--------------+-----------+
參見http://rextester.com/VOGNJ58311
如果退出碼W21是在該列中找到的最大值,那么您可以通過一次傳遞數據來獲得結果:
select
e.student, e.sid, count(distinct trunc(dated,'YYYY')) num_years
from enrollments e
group by e.student, e.sid
having count(distinct trunc(dated,'YYYY')) > 3
And max(exitcode) = 'W21'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.