简体   繁体   English

SQL-仅获取每个记录的特定日期

[英]SQL - Getting only a particular date for each record

I have a table called form with the following fields 我有一个名为表格的表格,其中包含以下字段

StudentID
form
date

Separately there is a student table containing their info, and StudentID is a foreign key from that table. 另外,有一个学生表包含他们的信息,而StudentID是该表的外键。

When a student moves form, a new entry is added for them in this table. 当学生移动表格时,将在此表中为他们添加一个新条目。 That way we have a record of when they moved. 这样我们就可以记录他们何时搬家。

I'm trying to make a query that will get all the information from the student table (for every student), and join to it the form they are currently in (ie, the form with the most recent date from the form table above). 我正在尝试进行一个查询,以从学生表(针对每个学生)获取所有信息,并将其当前所在的表单(即,上面表单表中日期最近的表单 )加入其中。

I can do it for individual students, but can't find a way to do it for the entire student table. 我可以为单个学生做这件事,但找不到为整个学生桌做这件事的方法。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Here is one method: 这是一种方法:

select s.*,
       max(f.date) as MostRecentDate,
       substring_index(group_concat(form order by date desc), ',', 1) as MostRecentForm
from student s join
     form f
     on s.StudentID = f.StudentId
group by s.StudentId;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM