SQL Query从多个标记返回最后一个值

时间:2013-10-01 09:08:12

标签: sql sql-server sql-server-2008-r2 greatest-n-per-group

我希望你能提供帮助。我是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

您可以给予任何建议。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER为每条记录提供一个rownumber(每个MeterTags.Name重置为0),然后只为每个名称选择第一个:

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;

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

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;

答案 1 :(得分: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