我希望有人能帮助我做到这一点。 我正在运行这个sql命令将一些数据放入我的Excel工作表中,这让我疯狂。
我有3张桌子需要合并
在事情开始失控之前,我实际上已经到了这里。 我可以得到sup和aud合并,我可以得到米和aud合并。虽然我无法选择有关供应的顶部仪表。
SELECT sup.*, aud.*, meters.*
FROM SuppliesData AS sup
INNER JOIN Audit As aud
ON sup.AuditID = aud.AuditID
WHERE sup.DeviceID = '14365'
INNER JOIN (
SELECT TOP 1
From MeterAudit AS meters
INNER JOIN aud
ON aud.AuditID=meters.AuditID
WHERE meters.DeviceID='14365' AND sup.AuditDate > meters.AuditDate// << I am so confused now...
ORDER by aud.AuditDate ASC
)
ORDER by aud.AuditDate ASC
我为尝试弄清楚我的烂摊子而道歉。
基本上, sup和meter都没有AuditDate字段。我需要将AuditDate字段应用于耗材,然后为每个耗材抓取最近的仪表。它是嵌套(你可能已经看到了)当前正在让我...所有我看到的错误我得到的是'围绕FROM的不正确的语法'
非常感谢任何帮助,
对于参考,以下代码完全正常
SELECT sup.*, aud.*
// - simply changing SuppliesData to MeterAudit changes everything perfectly.
FROM SuppliesData AS sup
INNER JOIN Audit As aud
ON sup.AuditID = aud.AuditID
WHERE DeviceID = '14365'
ORDER by aud.AuditDate ASC
JC
答案 0 :(得分:2)
请改为尝试:
SELECT sup.*, aud.*, meters.*
FROM SuppliesData AS sup
INNER JOIN Audit As aud ON sup.AuditID = aud.AuditID
AND sup.DeviceID = aud.DeviceID
INNER JOIN
(
SELECT AuditID, MAX(AuditDate) MaxDate
From MeterAudit
GROUP BY AuditID
) Maxa ON aud.AuditID = maxa.AuditID AND sup.AuditDate = maxa.AuditDate
WHERE sup.DeviceID = '14365'