mySQL - 仅选择连续出现的记录

时间:2017-01-30 23:12:07

标签: mysql

我正在处理一个处理学生记录的表格。基本上,我只需要选择至少连续3个未注册学期的学生的记录。

示例数据:

StudentID|Unregistered|Semester
10000000 |Y           |1
10000000 |Y           |2
10000000 |Y           |6
10000001 |Y           |2
10000001 |Y           |8
10000001 |Y           |9
10000001 |Y           |10
10000002 |Y           |1
10000002 |Y           |2
10000002 |Y           |3
10000002 |Y           |10

我只想从Student_ID 10000001和10000002中选择记录。

2 个答案:

答案 0 :(得分:0)

以下查询将为您提供连续学期的计数:

select s.id,
if(s.semester = @previousSem + 1 and @previousId = s.id, 
   @count := @count + 1, @count := 1) as count,
   @previousSem := s.semester as sem,
   @previousId := s.id as previousId
from sample s, (SELECT 
        @count := 1, 
        @previousSem := -1,
        @previousId := 0) a
order by s.id, s.semester

现在,您需要将此query加入主表(self join),并过滤掉包含3个或更多计数的记录,例如:

select s.id
from sample s join (select s.id,
if(s.semester = @previousSem + 1 and @previousId = s.id, 
   @count := @count + 1, @count := 1) as count,
   @previousSem := s.semester as sem,
   @previousId := s.id as previousId
from sample s, (SELECT 
        @count := 1, 
        @previousSem := -1,
        @previousId := 0) a
order by s.id, s.semester) s1
on s.id = s1.id
where s1.count >= 3
group by s.id;

这是 SQL Fiddle

P.S。为简洁起见,删除了unregistered列,您可以将其添加到实际查询中,并在内部查询中添加WHERE条件(WHERE registered = 'Y')。

答案 1 :(得分:0)

这个不是很灵活但很简单。并且它不使用会话变量(这是邪恶的):

select distinct r1.StudentID
from registrations r1
join registrations r2 
  on  r2.StudentID = r1.StudentID
  and r2.Semester  = r1.Semester + 1
join registrations r3
  on  r3.StudentID = r2.StudentID
  and r3.Semester  = r2.Semester + 1
where r1.Unregistered = 'Y'
  and r2.Unregistered = 'Y'
  and r3.Unregistered = 'Y';

更灵活的解决方案是:

set @num = 3;

select distinct r1.StudentID
from registrations r1
join registrations r2 
  on  r2.StudentID = r1.StudentID
  and r2.Semester  > r1.Semester
  and r2.Semester <= r1.Semester + @num - 1
where r1.Unregistered = 'Y'
  and r2.Unregistered = 'Y'
group by r1.StudentID, r1.Semester
having count(*) = @num - 1

该解决方案可让您轻松更改连续学期的数量。

http://rextester.com/HUUO33911