表格 - Employee.Status.XREF
Client Employee Date
198 Jon Doe 3/1/2009
198 Jon Doe 1/1/2009
表格 - Employee.Status.History
Client Employee Date Status
198 Jon Doe 5/21/2009 T
198 Jon Doe 3/1/2009 A
198 Jon Doe 1/1/2009 P
仅查询Employee.Status.History
,Employee.Status.XREF
和Client
匹配的Employee
和Date
中的记录。
仅返回Employee.Status.History
的记录,其中包含最长日期(client
乘以employee
)
在这种情况下,它将返回
Client Employee Date Status
198 Jon Doe 3/1/2009 A
答案 0 :(得分:4)
使用子选择&分组:
select b.*
from Employee.Status.History b,
( select client, employee, max(date) date
from Employee.Status.XREF
group by client, employee
) a
where b.client = a.client
and b.employee = a.employee
and b.date = a.date
内部查询选择最近的日期 外部查询返回关联客户端和员工在该日期的整个记录。
答案 1 :(得分:1)
这应该有效:
SELECT h.*
FROM Employee.Status.History h
INNER JOIN (
SELECT h.Client, MAX(h.Date) AS MaxDate
FROM Employee.Status.History h
INNER JOIN Employee.Status.XREF x ON h.Client = x.Client
AND h.Employee = x.Employee AND h.Date = x.Date
) q ON h.Client = q.Client
答案 2 :(得分:0)
MySQL的:
SELECT b.* FROM tableXREF a, tableSTATUS b
WHERE b.client = a.client
ORDER BY b.Date DESC
LIMIT 1
MSSQL:
SELECT TOP(1) b.field1, b.field2 etc. FROM tableXREF a, tableSTATUS b
WHERE b.client = a.client
ORDER BY b.Date DESC
我猜......
答案 3 :(得分:-1)
为什么不使用group by子句的连接?
select h.client,h.employee,max(h.date),h.Status
from Employee.Status.History h inner join Employee.Status.XREF x on
h.client=x.client and
h.employee=x.employee and
h.date=x.date
group by h.client,h.employee,h.Status