4

嗨,我需要为每个输入获取最新已知值的表。

我从这个开始

SELECT [MeterReadingId]
      ,[TimeStampUtc]
      ,[Val]
      ,[MeterReading].[InverterInputId]
      ,[Status]
  FROM [Project].[dbo].[MeterReading]
  inner join InverterInput on [MeterReading].InverterInputId = [InverterInput].InverterInputId
  inner join Inverter on [InverterInput].InverterId = [Inverter].InverterId 
  where [InverterInput].InputName = 'DayYield' and [Inverter].PlantId = 1

当然现在我得到了属于名称'DayYield和plantId = 1的输入的所有值我的问题是如何只获得那些具有最新[TimeStampUtc]的值的表

换句话说:获取所有那些属于名称'DayYield和plantId = 1的输入并且最后插入到表中的[Val]。

4

3 回答 3

9

一个选项是 a cross apply,例如:

select  *
from    Devices d
cross apply
        (
        select  top 1 *
        from    Measurements m
        where   m.device_id = d.id
        order by
                m.timestamp desc
        ) m
于 2013-04-28T11:22:54.963 回答
7

为此,您可以使用排名功能ROW_NUMBER()例如。像这样的东西:

WITH CTE
AS
(
    SELECT [MeterReadingId]
          ,[TimeStampUtc]
          ,[Val]
          ,m.[InverterInputId]
          ,[Status]
          ,ROW_NUMBER() OVER(PARTITION BY m.InverterInputId 
                             ORDER BY m.[TimeStampUtc] DESC) AS RN
      FROM [Project].[dbo].[MeterReading] AS m
      inner join InverterInput AS ii on m.InverterInputId = ii.InverterInputId
      inner join Inverter      AS i  on ii.InverterId     = i.InverterId 
      where ii.InputName = 'DayYield' and i.PlantId = 1
) 
SELECT *
FROM CTE
WHERE RN = 1;

使用ORDER BY m.[TimeStampUtc] DESC将为您提供最新的[TimeStampUtc].

请注意:我不知道您正在使用的表结构,但您可能需要在PARTITION BY子句中使用另一列来分组,而不是MeterReadingId.

于 2013-04-28T11:26:49.637 回答
0

我发现交叉应用功能更容易阅读。这也意味着您维护正常查询的基本结构。

update cc
set cc.OutCC = oocd.CC, cc.Outcel = oocd.cel, 
    cc.Outcd = oocd.cd, cc.Outrn = oocd.rn, 
    cc.outidate = oocd.idate, cc.outtdate = oocd.tdate
from @CbC cc 
cross apply ( 
    select top 1 * from @OutC ocd
    where substring(ocd.rn,LEN(ocd.rn) - 9,9) = substring(cc.rn,LEN(cc.rn) - 9,9) and (ocd.cdate between cc.idate and DATEADD(hh,1,cc.idate)) and ocd.cdate < cc.tdate and ocd.cel like '%' + cc.line + '%' collate database_default  
order by ocd.idate
) oocd
于 2014-03-31T22:27:17.133 回答