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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With