2012-06-30 58 views
5

這裏是我想要轉換成的LINQ查詢:我如何轉換這個SQL查詢到LINQ(OVER(PARTITION BY日期))

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

你到目前爲止嘗試過什麼? Stackoverflow不是一個網站,您只需發佈內容並告訴人們「修復它」或「轉換此」,因此在將來您提出問題時,請考慮一下。 – Joakim

+0

請看更新。 –

+0

根據我的經驗,我發現linqer是將t-sql轉換爲linq的非常有用的工具。 http://www.sqltolinq.com/ - 帶有10天免費試用版。 –

回答

3

第一執行查詢,而無需聚合:

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

這將產生如數據庫查詢相同的效果。上面的代碼可能包含錯誤,因爲我只在這裏寫它。

+0

令人驚歎的1百萬謝謝!奇蹟般有效! –

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

在你的情況,你可能必須先一起加入這兩個表,而分組,然後在連接的表結果上運行上述相同的概念。