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

标签 c# sql asp.net-mvc linq entity-framework

这是我试图转换成 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 代码;我无法按日期进行 OVER PARTITION。

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) });

最佳答案

先执行查询而不聚合:

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) };

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

关于c# - 如何将此 SQL 查询转换为 LINQ (OVER (PARTITION BY Date)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277695/

相关文章:

c# - 如何从 Excel 工作表生成图表?

c# - 使用 c# 将纯文本(标题)导出到 excel

c# - asp.net MVC 中特定于部署的资源?

c# - 保存 DataGridView

c# - 如何在点击ASP日历日期时显示Popup窗体?

sql - 有事务的内存缓存?

sql - 如何解决杀死/回滚状态问题

mysql帮忙做报告

c# - 在每个 Controller 操作之前/之后执行代码

asp.net-mvc - Azure 文件存储/索引解决方案