如何将Mssql查询转换为LINQ?

时间:2018-05-18 06:13:45

标签: c# linq linq-to-sql

如何将此查询转换为LINQ表达式?

WITH MyRowSet
AS
(
SELECT  RH.Id,RH.Reputation,RH.ReputationIpId,CheckDateTime,IpGroup.Name,ROW_NUMBER()
OVER (PARTITION BY ReputationIpId ORDER BY CheckDateTime DESC) AS RowNum
FROM dbo.ReputationHistory As RH
INNER JOIN dbo.ReputationIps as IP ON RH.ReputationIpId=IP.Id
INNER JOIN dbo.ReputationMonitorGroups as IpGroup ON IP.ReputationMonitorGroupId=IpGroup.Id
)
SELECT AVG(Reputation),Name RowNum FROM MyRowSet WHERE RowNum <= 5  Group By RowNum,Name ORDER BY RowNum

这个查询在做什么? 最后需要五个&#34;声誉&#34;记录每个&#34; IP&#34;在历史上 然后我们得到IpGroup的平均值。

表达的第一部分是:

reputationHistoryRepository.GetAll()
                .GroupBy(el => el.ReputationIpId)
                .Select(grp => grp
                    .OrderBy(gr => gr.CheckDateTime)
                    .TakeLast(lastRecordNum))

每个IP需要最后5条记录。然后我需要得到每一行的平均值。例如,所有IP的第一行的平均值,第二行等等。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。这是答案。

var result = _reputationHistoryRepository.GetAll()
            .Include(ips => ips.ReputationIp)
            .ThenInclude(ipGroups => ipGroups.ReputationMonitorGroup)
            .GroupBy(repHistory => repHistory.ReputationIpId)
            .Select(group => group
                .OrderBy(repHistory => repHistory.CheckDateTime)
                .TakeLast(countOfRecords)
                .Select((reputationHistory, index) => new
                {
                    GroupName = reputationHistory.ReputationIp.ReputationMonitorGroup.Name,
                    ReputationHistoryObject = reputationHistory,
                    RowNum = index
                }))
            .SelectMany(reputationHistory => reputationHistory)
            .GroupBy(reputationHistory => new
            {
                reputationHistory.RowNum,
                reputationHistory.GroupName
            })
            .Select(reputationHistoryGroup => new
            {
                Reputation = reputationHistoryGroup.Average(x => x.ReputationHistoryObject.Reputation),
                GrpName = reputationHistoryGroup.Key.GroupName,
                RowNum = reputationHistoryGroup.Key.RowNum
            });