Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here's the query I'm trying to convert into 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]

Thanks for any help.

UPDATE: Here is the Linq code I'm trying it on; I cannot make the OVER PARTITION by Date.

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) });
like image 336
Martin Gemme Avatar asked Jun 30 '12 21:06

Martin Gemme


1 Answers

Execute query first without aggregation:

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

Then calculate sum

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

This should produce the same effect as database query. Code above may contain errors, because I wrote it only here.

like image 114
LukLed Avatar answered Oct 24 '22 12:10

LukLed