【问题标题】:Linq to SQL: Sum with multiple columns selectLinq to SQL:多列求和选择
【发布时间】:2013-10-19 15:16:16
【问题描述】:

想把下面的SQL代码转成linq to 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),
                }
              );

如何选择其他两列?我错过了什么?

【问题讨论】:

  • 这个问题是关于.net code for linq-to-sql,怎么会是服务器故障?
  • 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}
  • @vittore 抱歉标签中的错字...
  • @vittore 我不确定你的代码是做什么的......我似乎没有看到总和部分......

标签: c# .net linq linq-to-sql


【解决方案1】:

其实你的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)
             };

【讨论】:

    【解决方案2】:

    这是您的 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)} 
    

    假设您在 ctx 变量中有 linq2sql 上下文,并且其中有您的表。

    【讨论】:

    • 对不起,它没有解决我的问题。我只需要按 agent_code 分组,但显示 holder_name、agent_code 和 sum(total)
    • holder_name 来自哪里?如果您没有将持有人姓名与代码一起分组,则您的原始 sql 语句无效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多