2

首先,我是一个完整的 SQL 初学者,并且已经深入了解了一点!我正在学习,我犯的每一个错误或我提出的问题都希望能帮助我发展......请善待:)

我有一个提取电表读数和其他信息的工作查询。我正在为每个站点找到最新的阅读内容。这是目前的查询:

PARAMETERS [Site Group] Text ( 255 );
SELECT 
Lookup.Lookup_Name AS [Group], 
Contacts.Name AS Site, 
Points.Number AS MPAN, 
Max(DataElectricity.Date) AS MaxDate, 
DataElectricity.M1_Present, 
DataElectricity.M2_Present, 
DataElectricity.M3_Present, 
DataElectricity.M4_Present, 
DataElectricity.M5_Present, 
DataElectricity.M6_Present, 
DataElectricity.M7_Present, 
DataElectricity.M8_Present,
DataElectricity.Direct
FROM 
DataElectricity INNER JOIN (Lookup INNER JOIN (Points INNER JOIN Contacts ON Points.Contacts_Id = Contacts.Id) ON Lookup.Lookup_Id = Contacts.Group_1) ON DataElectricity.Point_Id = Points.Id
WHERE
((DataElectricity.Direct)='D')
GROUP BY 
Lookup.Lookup_Name, Contacts.Name, Points.Number, DataElectricity.M1_Present, DataElectricity.M2_Present, DataElectricity.M3_Present, DataElectricity.M4_Present, DataElectricity.M5_Present, DataElectricity.M6_Present, DataElectricity.M7_Present, DataElectricity.M8_Present, DataElectricity.Direct
ORDER BY 
Lookup.Lookup_Name, Contacts.Name, Max(DataElectricity.Date) DESC;

但是,这会返回站点的所有读数,而不仅仅是最新的……我敢肯定这很简单,但我想不通。

任何建议或指导都将不胜感激:)

4

2 回答 2

1

你不能只使用 top 1 来获得第一个结果吗?

SELECT top 1 ... 
于 2013-07-23T14:36:58.973 回答
1

我使用 caspian 对 SELECT top 1 的建议进一步改进了代码......但我正在努力进一步完善它并产生我需要的结果。

    PARAMETERS [Site Group] Text ( 255 );
    SELECT 
    Lookup.Lookup_Name, 
    Contacts.Name AS Site, 
    Points.Number AS MPAN, 
    DataElectricity.M1_Present, 
    DataElectricity.M2_Present, 
    DataElectricity.M3_Present, 
    DataElectricity.M4_Present, 
    DataElectricity.M5_Present, 
    DataElectricity.M6_Present, 
    DataElectricity.M7_Present, 
    DataElectricity.M8_Present,
    DataElectricity.Direct

    FROM 
    (
    SELECT TOP 1 DataElectricity.Date AS MaxDate, 
            DataElectricity.M1_Present, 
            DataElectricity.M2_Present, 
            DataElectricity.M3_Present, 
            DataElectricity.M4_Present, 
            DataElectricity.M5_Present, 
            DataElectricity.M6_Present, 
            DataElectricity.M7_Present, 
            DataElectricity.M8_Present,
            DataElectricity.Point_id
    FROM 
    DataElectricity 
    ORDER BY MaxDate DESC
    )

    DataElectricity INNER JOIN (Lookup INNER JOIN (Points INNER JOIN Contacts ON Points.Contacts_Id = Contacts.Id) ON Lookup.Lookup_Id = Contacts.Group_1) ON DataElectricity.Point_Id = Points.Id
    WHERE 
    ((Lookup.Lookup_Name)=Lookup_Name) 
    ORDER BY 
    Lookup.Lookup_Name, Contacts.Name, MaxDate DESC;

我确实有一个 Google Drive 文件,其中显示了数据表的一个小示例和所需的结果,并希望有一个关于表如何连接的清晰指南。

https://docs.google.com/file/d/0BybrcUCD29TxWVRsV1VtTm1Bems/edit?usp=sharing

实际数据包含数百个站点组,每个站点组可能包含数百个站点。

我希望我的最终用户能够从 Lookup.Lookup_Name 列表中选择站点组名称,并让它返回所有相关的站点和读数。

....我真的希望这是有道理的!

于 2013-08-07T11:04:52.257 回答