2013-10-19 77 views
1

我想下面的SQL代碼轉換成LINQ to SQL的,但似乎無法找到一種方法LINQ到SQL:多列求和選擇

select holder_name,agent_code,sum(total) 
from agent_commission 
group by agent_code 

誰能幫助我?有一段時間我有點陷入這種困境。

在此先感謝

更新: 我嘗試以下

var query = (from p in context.Agent_Commissions 
       group p by new 
       { 
        p.agent_code 
       } 
       into s 
       select new 
       { 
        amount = s.Sum(q => q.total), 
       } 
      ); 

如何選擇另外兩列?我錯過了什麼?

+1

這個問題是.net代碼爲linq-to-sql,它是如何來它屬於服務器故障? – vittore

+0

'from a ctx.agent_code 將a組合爲a.holder_name,a.code組合成合計 select {holder_name = a.holder_name,code = a.code,total = totals}' – vittore

+0

@vittore對於標籤中的拼寫錯誤... – Bahdeng

回答

0

這是你的LINQ查詢

from a in ctx.agent_code 
group a by a.holder_name, a.code into totals 
select { holder_name = a.holder_name, 
     code = a.code, 
     total = totals.Sum(t=>t.total)} 

既然你有LINQ2SQL上下文ctx變量,它有你的表吧。

+0

對不起,它不能解決我的問題。我只需要通過agent_code分組,但顯示holder_name,agent_code和總和 – Bahdeng

+0

其中holder_name來自哪裏?如果您沒有將持有者名稱與代碼一起放入組中,那麼您的原始sql語句無效 – vittore

3

其實你SQL query作品只有holder_nameagent_code的對應關係是1-1,否則Group by agent_code將無法​​正常工作。所以你的linq query應該是這樣的:

var query = from p in context.Agent_Commissions 
      group p by p.agent_code into s 
      select new { 
       holder_name = s.FirstOrDefault().holder_name, 
       agent_code = s.Key, 
       amount = s.Sum(q => q.total) 
      };