繁体   English   中英

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

[英]How can I convert this SQL Query into LINQ (OVER (PARTITION BY Date))

这是我想要转换成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) });

首先执行查询而不进行聚合:

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

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

我已经回答了类似的线程: LINQ to SQL和有序结果的运行总计

在那个线程上它是这样的:

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

在您的情况下,您可能必须在分组时首先将两个表连接在一起,然后在连接的表结果上运行上面的相同概念。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM