2017-10-09 66 views
-4

無法弄清楚如何在VB中的LINQ中編寫此查詢。如何在VB.Net中編寫此查詢LINQ

SELECT 
    createdon, SUM(LoggedTime), SUM(cost) 
FROM TimeLedger 
WHERE userid = v_UserId and YEAR(createdon) = v_Year 
GROUP BY createdon 
ORDER BY createdon DESC; 

這是我的第一次努力

result = (from p in db.TimeLedgers where p.userid=v_userid and year(p.createdon)= p_year group by createdon order by createdon select cost).sum() 

回答

1

的語法的GroupBy在LINQ有點不可思議。我沒有任何辦法來測試這一點,但試試這個...

Dim result = (From p In db.TimeLedgers Where p.userid = v_userID AndAlso p.createdon.Year = p_year 
         Group By p.createdon Into Group 
         Order By p.createdon Descending 
         Select createdon, TotalTime = Group.Sum(Function(v) v.LoggedTime), TotalCost = Group.Sum(Function(v) v.cost)) 
+2

你在'訂單留出了'Descending'根據',用於訪問年份成員的VB(和C#)語法是'.Year',並且您應該在'Group'之後'Order By',因爲您不應該指望保持原始順序的Group。 – NetMage

1

使用正確的VB語法,並建議排序,

Dim result = From p In db.TimeLedgers Where p.userid = v_userID And p.createdon.Year = p_year 
      Group By p.createdon Into Group 
      Order By createdon Descending 
      Select createdon, TotalTime = Group.Sum(Function(tl) tl.LoggedTime), TotalCost = Group.Sum(Function(tl) tl.cost)