这是表结构(相关位):
我正在尝试找到与clientID上的声明和声明日期匹配的contactLog条目(实际上在8小时内)。这就是我想出的:
SELECT
D.ClientID
D.DeclarationID
CL.ContactDescription,
CL.ContactDate,
FROM Declarations D
INNER JOIN (Contacts C
INNER JOIN (PartialContacts PC
INNER JOIN ContactLogs CL
ON PC.ContactPartID = CL.ContactPartID )
on PC.ContactID = C.ContactID
)
ON C.ClientID = D.ClientID AND DATEDIFF(hour, D.DeclarationDate, CL.ContactDate) < 8
但是,连接功能不正常,因为我为CL.ContactDate返回了不匹配的日期,并且很明显它只返回CL中该患者ID的每一行。我想......我不确定会出现什么问题。
答案 0 :(得分:0)
感谢Damien:
我没有指定datediff的下限,因此匹配无法正常工作。显然,连接很好:
SELECT
D.ClientID
D.DeclarationID
CL.ContactDescription,
CL.ContactDate,
FROM Declarations D
INNER JOIN (Contacts C
INNER JOIN (PartialContacts PC
INNER JOIN ContactLogs CL
ON PC.ContactPartID = CL.ContactPartID )
on PC.ContactID = C.ContactID
)
ON C.ClientID = D.ClientID AND DATEDIFF(hour, D.DeclarationDate, CL.ContactDate) < 8 DATEDIFF(hour, D.DeclarationDate, CL.ContactDate) > 0.1
答案 1 :(得分:0)
SELECT
D.ClientID
D.DeclarationID
CL.ContactDescription,
CL.ContactDate
FROM Declarations D
INNER JOIN Clients CL ON D.ClientID=CL.ClientID
INNER JOIN Contacts CO ON CL.ClientID=CO.ClientID
INNER JOIN PartialContact PC ON PC.ContactID=CO.ContactID
INNER JOIN ContactLog CL ON CL.ContactPartID=PC.ContactPartID
WHERE DATEDIFF(hour, D.DeclarationDate, CL.ContactDate) BETWEEN 0 AND 8