1

我希望你能提供帮助。我是 SQL 的新手,所以这个开始困扰我。

目前,我每天都在为Meter Name. 此数据当前记录在包含列的表中TimeStamp, Name, Value。但是,我想创建一个查询,该查询仅返回针对Name表中每个记录的最新(最后)值。

到目前为止,我已经构建了这个查询,但Top 1语法似乎不是我需要的。

SELECT Top 1 (DataLog.Timestamp), MeterTags.Name, DataLog.Value
FROM Meters
INNER JOIN MeterTags
ON Meters.MeterId = MeterTags.MeterId
INNER JOIN DataLog
ON MeterTags.MeterTagId = DataLog.MeterTagId
WHERE Meters.MeterTypeId = 8
GROUP By MeterTags.Name, DataLog.Timestamp

您可以提供的任何建议将不胜感激。

提前致谢。

4

2 回答 2

1

您可以使用ROW_NUMBER给每条记录一个行号(为 each 重置为 0 MeterTags.Name),然后为每个名称选择第一个:

WITH CTE AS
(   SELECT  DataLog.Timestamp, 
            MeterTags.Name, 
            DataLog.Value,
            RowNumber = ROW_NUMBER() OVER(PARTITION BY MeterTags.Name 
                                        ORDER BY DataLog.TimeStamp DESC)
    FROM    Meters
            INNER JOIN MeterTags
                ON Meters.MeterId = MeterTags.MeterId
            INNER JOIN DataLog
                ON MeterTags.MeterTagId = DataLog.MeterTagId
    WHERE   Meters.MeterTypeId = 8
)
SELECT  CTE.Timestamp,
        CTE.Name,
        CTE.Value
FROM    CTE
WHERE   CTE.RowNumber = 1;

另一种解决方案是使用TOP 1内部APPLY

SELECT  DataLog.Timestamp, 
        MeterTags.Name, 
        DataLog.Value
FROM    Meters
        INNER JOIN MeterTags
            ON Meters.MeterId = MeterTags.MeterId
        CROSS APPLY
        (   SELECT  TOP 1 TimeStamp, Value
            FROM    DataLog
            WHERE   MeterTags.MeterTagId = DataLog.MeterTagId
            ORDER BY TimeStamp DESC
        ) DataLog
WHERE   Meters.MeterTypeId = 8;
于 2013-10-01T09:12:49.760 回答
0

试试下面的查询

select Timestamp,Name,Value
from 
(

SELECT (DataLog.Timestamp), MeterTags.Name, DataLog.Value,rownum,ROW_NUMBER() OVER 
 (PARTITION BY MeterTags.Name ORDER BY DataLog.Timestamp desc) AS rownum FROM Meters
 INNER JOIN MeterTags
 ON Meters.MeterId = MeterTags.MeterId
 INNER JOIN DataLog
 ON MeterTags.MeterTagId = DataLog.MeterTagId
)data
   where rownum=1
于 2013-10-01T09:39:35.747 回答