SQL内部联接与前1名

时间:2013-04-28 11:21:02

标签: sql sql-server-2008 tsql

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

我从这个

开始
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]并最后插入表格。

3 个答案:

答案 0 :(得分:9)

一个选项是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

答案 1 :(得分:7)

为此,您可以使用ranking functionsROW_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中进行分组。

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