0

我希望有人可以帮助我解决这个问题。我目前正在运行这个 sql 命令来获取一些数据到我的 excel 工作表中,这让我发疯了。

我有 3 张桌子需要合并

  • sup = 每小时供应数据
  • 审计 = 记录事情到达的时间(sup & Meters)
  • 米 = 米的每日数据

在事情开始失控之前,我基本上到达了这里。我可以让 sup 和 aud 合并,我可以让 Meters 和 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 和 Meters 都没有 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

4

1 回答 1

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' 
于 2012-12-08T08:44:10.603 回答