Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL inner join with top 1

Hi I need to get table of latest known value one for each input.

I started with this

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

off course now i got all values which belong to inputs of name 'DayYield and plantId =1 My question is how can got table only of those values which have latest [TimeStampUtc]

Other words: get all those [Val] which belong to input of name 'DayYield and plantId =1 and are last inserted into table.

like image 221
kosnkov Avatar asked Dec 05 '22 11:12

kosnkov


2 Answers

One option is a cross apply, like:

select  *
from    Devices d
cross apply
        (
        select  top 1 *
        from    Measurements m
        where   m.device_id = d.id
        order by
                m.timestamp desc
        ) m
like image 89
Andomar Avatar answered Dec 24 '22 07:12

Andomar


For this, you can use the ranking functions, ROW_NUMBER() for example. Something like this:

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;

Using ORDER BY m.[TimeStampUtc] DESC will give you the latest [TimeStampUtc] .

Note that: I don't know about the tables' structures you are using, but you might need to use another column to group by in the PARTITION BY clause instead of MeterReadingId.

like image 27
Mahmoud Gamal Avatar answered Dec 24 '22 07:12

Mahmoud Gamal