我有一个有多列的学生表,但是,我只对重新注册列和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
基本上我只需要拉巴特和荷马,因为他们毕业前四年就在区内。丽莎不会被拉。
我很难过如何做到这一点,任何帮助都会很棒。
由于
答案 0 :(得分:0)
像这样的东西,它不会很快,但它会起作用:
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)
答案 1 :(得分:0)
带有having子句的group应该足够了。将日期截断为年份并计算不同应该解决的年数。
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
工作如果exitcode 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'