加入两个表,这样只能连接第二个表中的一行

时间:2016-06-07 02:26:55

标签: sql access

我有两个表,MachineWiseMaterial(字段:McMatID)和MaterialIssueRegister(字段:McMatID,IssueDate,IssueTime,EMR)。 我想要每个McMatID的最后一期日期,时间和EMR。

对于任何使用SELECT TOP 1的McMatID,我都能找到相同的内容,如下所示。

SELECT TOP 1 McMatID, IssueDate, IssueTime, EMR 
FROM MaterialIssueRegister 
WHERE McMatID = [some value, eg. 1] 
ORDER BY IssueDate DESC, IssueTime DESC, EMR DESC;

但是当我试图加入这两张牌桌时,我没有得到理想的结果。

SELECT MachineWiseMaterial.McMatID, b.IssueDate, b.EMR 
FROM MachineWiseMaterial 
LEFT JOIN (SELECT TOP 1 McMatID, IssueDate, IssueTime, EMR 
FROM MaterialIssueRegister  
ORDER BY IssueDate DESC, IssueTime DESC, EMR DESC) AS b
ON MachineWiseMaterial.McMatID = b.McMatID;

上述查询仅返回IssueDate为Max的McMatID,而不是每个McMatID的最大日期。

2 个答案:

答案 0 :(得分:0)

你可以尝试这样......

SELECT MachineWiseMaterial.McMatID, b.IssueDate, b.EMR 
FROM MachineWiseMaterial m1
where m1.McMatId=(SELECT TOP 1 McMatID
FROM MaterialIssueRegister  m2
where m2.McMatId=m1.McMatId
ORDER BY IssueDate DESC, IssueTime DESC, EMR DESC)

答案 1 :(得分:0)

这样的事情:

选择MachineWiseMaterial.McMatID,b.EMR,max(b.IssueDate) 来自MachineWiseMaterial LEFT JOIN MaterialIssueRegister b ON MachineWiseMaterial.McMatID = b.McMatID group by MachineWiseMaterial.McMatID,b.EMR