Microsoft SQL 服务器:连接两个表的最大日期
Microsoft SQL Server : max date joining two tables
我正在尝试加入两个 table,同时从一个中提取最大日期。
我有一个学生 table 和一个交流 table。每个学生在学生中都是独一无二的table,有很多交流条目。
我想创建一个 SQL 脚本来提取每个学生的 ID、姓名、最近的通信日期以及该日期的通信消息。
我可以使用 max(comm_date)
和 group by
提取每个学生的最新日期,但是在提取相应的通信消息时事情变得混乱(很多重复)。
Table: 学生
studentid, name
Table: 通讯
studentid, comm_date, comm_msg
结果:
student.studentid, student.name, communications.comm_date, communications.comm_msg
如何拉取给定max(comm_date)
对应的通信消息?
这应该可以满足您的需求。我不知道通过嵌套子查询执行此操作是否会影响性能,但我喜欢这种简洁的语法:
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
这应该能满足您的需求...
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
此外,我建议为您的学生 table 添加一列以记录最近的通信日期(如果通信具有自动递增列,例如同一天的多个条目,甚至是 ID)。然后,通过对通信 table 的插入触发器,您使用最新日期(或通信 ID)更新学生 table。然后你永远不需要像这个一样多次重新查询 MAX() 并重新加入。
我正在尝试加入两个 table,同时从一个中提取最大日期。 我有一个学生 table 和一个交流 table。每个学生在学生中都是独一无二的table,有很多交流条目。
我想创建一个 SQL 脚本来提取每个学生的 ID、姓名、最近的通信日期以及该日期的通信消息。
我可以使用 max(comm_date)
和 group by
提取每个学生的最新日期,但是在提取相应的通信消息时事情变得混乱(很多重复)。
Table: 学生
studentid, name
Table: 通讯
studentid, comm_date, comm_msg
结果:
student.studentid, student.name, communications.comm_date, communications.comm_msg
如何拉取给定max(comm_date)
对应的通信消息?
这应该可以满足您的需求。我不知道通过嵌套子查询执行此操作是否会影响性能,但我喜欢这种简洁的语法:
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
这应该能满足您的需求...
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
此外,我建议为您的学生 table 添加一列以记录最近的通信日期(如果通信具有自动递增列,例如同一天的多个条目,甚至是 ID)。然后,通过对通信 table 的插入触发器,您使用最新日期(或通信 ID)更新学生 table。然后你永远不需要像这个一样多次重新查询 MAX() 并重新加入。