如何将此SQL查询转换为LINQ(OVER(PARTITION BY Date))?

9

以下是我试图转换为Linq的查询:

SELECT R.Code, 
       R.FlightNumber, 
       S.[Date], 
       S.Station,
       R.Liters, 
       SUM(R.Liters) OVER (PARTITION BY Year([Date]), Month([Date]), Day([Date])) AS Total_Liters
FROM S INNER JOIN
               R ON S.ID = R.SID
WHERE (R.Code = 'AC')
AND FlightNumber = '124'
GROUP BY  Station, Code, FlightNumber, [Date], Liter
ORDER BY R.FlightNumber, [Date]

感谢您的帮助。

更新:这里是我正在使用的Linq代码;我无法按日期进行分区。

var test = 
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID                       

orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber

group record by new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1} into g

select new { g.Key.Station, g.Key.Code, g.Key.FlightNumber, g.Key.Date, AmmountType1Sum = g.Sum(record => record.AmountType1) });

你到目前为止尝试了什么? StackOverflow不是一个你只需发布某些内容并告诉人们“修复它”或“转换它”的网站,因此在未来当你提问时,请考虑这一点。 - Joakim
根据我的经验,我发现Linqer是将T-SQL转换为LINQ的非常有用的工具。http://www.sqltolinq.com/ - 附带10天免费试用。 - Jeremy Wiggins
1
@JeremyWiggins OVER PARTITION 在 Linqer 中无法识别,我很抱歉。 - Martin Gemme
你可以轻松地分两步完成它。在不使用 SUM 的情况下执行查询,然后在客户端(即 .NET 代码)计算 SUM。 - LukLed
@LukLed 我试了好几个小时都没做出来。我尝试创建一个滚动函数,但是我无法完成它。我想要按日期求和的东西(例如,按日期分区)。 - Martin Gemme
2个回答

5

首先执行没有聚合的查询:

var test = 
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID                       

orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber

select new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1};

然后计算总和。
var result = 
    from row in test
    select new {row.Station, row.Code, row.FlightNumber, row.Date, row.AmountType1, 
    AmountType1Sum = test.Where(r => r.Date == row.Date).Sum(r => r.AmountType1) };

这应该产生与数据库查询相同的效果。上面的代码可能包含错误,因为我只是在这里编写它。


1

我在一个类似的帖子上回答过:LINQ to SQL and a running total on ordered results

在那个帖子中是这样的:

var withRuningTotals = from i in itemList    
                   select i.Date, i.Amount,    
                          Runningtotal = itemList.Where( x=> x.Date == i.Date).
                                                  GroupBy(x=> x.Date).
                                                  Select(DateGroup=> DateGroup.Sum(x=> x.Amount)).Single();

在你的情况下,你可能需要先将两个表连接在一起,然后在分组时再对连接后的表结果运行上述相同的概念。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接