我有一个包含以下字段的数据集:
IntervalPeriodTimestamp
RegisterTypeCode
ReadingReplacementVersion
IntervalValue
我每30分钟收到一次读数,但有时会更换这些读数,并且读取位移量会增加。
使用LINQ如何每半小时只返回一次最大读取替换的列表?
我试过了:
db.IntervalInformations
.Where(ii => ii.ChannelInformation.RegisterTypeCode == "62")
.OrderBy(ii => ii.IntervalPeriodTimestamp)
.ThenBy(ii => ii.ChannelInformation.Meter.messageType342.ReadingReplacementVersionNumber)
.ToList();
这将返回按Interval Period Timestamp排序的列表,然后按Replacement Version排序,但我只想返回带有MAX的间隔信息列表。我已经能够使用代码在SQL中实现这一点:
WITH CTE AS
(
select SerialNumber, RegisterTypeCode, IntervalStatusCode, UOM_Code,
IntervalPeriodTimestamp, ReadingReplacementVersionNumber, IntervalValue,
RN = ROW_NUMBER()
OVER (PARTITION BY IntervalPeriodTimestamp
ORDER BY ReadingReplacementVersionNumber desc)
from MarketMessage as a
inner join messageType342 as b on a.MarketMessageID = b.MarketMessageID
inner join Meter as c on b.messageType342ID = c.MessageType342ID
inner join ChannelInformation as d on c.MeterID = d.MeterID
inner join IntervalInformation as e on d.ChannelInformationID = e.ChannelInformationID
where MPRN = 101010101010
and CAST(IntervalPeriodTimestamp as date) between '1 feb 2018' and '28 feb 2018'
and RegisterTypeCode = 62
)
select * from CTE
WHERE RN = 1
不确定如何将其转换为LINQ语句
答案 0 :(得分:0)
尝试这样的事情:将您的项目分组到您只想要一条记录的不同组中,按照后代顺序按ReadingReplacementVersionNumber
排序记录,并获得每组中的第一条记录。使用某些代码更容易理解:
db.IntervalInformations
.Where(ii => ii.ChannelInformation.RegisterTypeCode == "62")
.OrderByDescending(ii => ii.ReadingReplacementVersionNumber )
.GroupBy(x => new { x.SerialNumber, x.RegisterTypeCode, x.IntervalStatusCode })
.Select(g => g.First());
真实查询中GroupBy
中的属性列表可能有所不同。您必须正确定义组成组的条件。在GroupBy
列表中包含在每个组中具有相同值的属性组合,以及其他组中的不同值。