0

我正在尝试加入两个表,同时从一个表中提取最大日期。我有一张学生桌和一张交流桌。每个学生在学生表中都是唯一的,并且有许多通信条目。

我想创建一个 SQL 脚本来提取每个学生的 ID、姓名、最近的通信日期以及该日期的通信消息。

我可以使用max(comm_date)and为每个学生提取最新日期group by,但是在提取相应的通信消息时事情会变得一团糟(很多重复)。

表:学生

studentid, name

表:通讯

studentid, comm_date, comm_msg

结果:

student.studentid, student.name, communications.comm_date, communications.comm_msg

如何拉取给定的相应通信消息max(comm_date)

4

2 回答 2

1

这应该可以满足您的需求。我不知道通过嵌套子查询执行此操作是否会影响性能,但我喜欢这种简洁的语法:

SELECT 
   s.studentid, 
   s.name, 
   LastCommDate = MAX(c.comm_date), 
   LastCommMessage = (SELECT comm_msg FROM Communications WHERE studentid = s.studentid AND comm_date = MAX(c.comm_date))
FROM Student AS s 
INNER JOIN Communications AS c
ON s.studentid = c.studentid
GROUP BY s.studentid, s.name
于 2016-04-20T22:38:49.677 回答
0

这应该得到你需要的......

select
      s.studentid,
      s.name,
      c2.comm_date,
      c2.comm_msg
   from
      Student s
         LEFT JOIN 
         ( select 
                 c1.studentid,
                 max( c1.comm_Date ) as MaxDate
              from
                 Communications c1
              group by
                 c1.studentid ) PreMax
            on s.studentid = PreMax.StudentID
            LEFT JOIN Communications c2
               on PreMax.StudentID = c2.StudentID
              AND PreMax.MaxDate = c2.comm_Dat

此外,我建议在您的学生表中添加一个最近通信日期的列(如果通信具有自动增量列,例如同一天的多个条目,甚至是一个 ID)。然后,通过对通信表的插入触发器,您使用最新日期(或通信 ID)更新学生表。然后你永远不需要像这个一样不断地重新查询 MAX() 并重新加入。

于 2016-04-20T22:41:13.530 回答