【问题标题】:Convert T-SQL into LINQ Lambda将 T-SQL 转换为 LINQ Lambda
【发布时间】:2013-09-12 12:18:45
【问题描述】:

如果需要,我如何在 LINQ lambda 表达式或查询语法中编写此查询?我已经尝试了一段时间了。多个连接使其变得困难。 join总记录超过2000条,最终结果应该是15条左右

select 
    year([date]), 
    month([date]),
    sum(ot.rate)
from s as s 
join cs cs on cs.s_id= s.id
join ot ot on ot.id = cs.o_id
group by
    year([date]), 
    month([date])

这是我得到的最接近但不会编译的。我无法从选择块中访问 ot 属性。

    var query = from se in table_se
        join cs in table_cs on se.Id equals cs.S_Id
        join ot in table_ot on cs.O_Id equals ot.Id
        group se by new { se.Date.Year, se.Date.Month } into grp 
        select new
        {
            grp.Key.Year,
            grp.Key.Month,
            grp.Sum(ot.Rate)
        };

【问题讨论】:

  • 安装 Resharper,它会完成你的工作 :)
  • 如果您已经“尝试了一段时间”,那么大概您应该能够告诉我们您尝试了什么以及出了什么问题。可能其他人会建议你已经尝试过的东西......
  • @JonSkeet 我已经更新了我能得到的最接近的值。

标签: c# sql-server linq tsql lambda


【解决方案1】:

你非常接近 - Enumerable.Sum 接受谓词

var query = from se in table_se
        join cs in table_cs on se.Id equals cs.S_Id
        join ot in table_ot on cs.O_Id equals ot.Id
        group ot by new { se.Date.Year, se.Date.Month } into grp 
        select new
        {
            Year = grp.Key.Year,
            Month = grp.Key.Month,
            Sum = grp.Sum(x => x.Rate)
        };

【讨论】:

  • 当我尝试 x 属性是 'se' 而不是 'ot' 这是 Rate 字段的位置
  • 好的。需要将 'group se by new' 更改为 'group ot by new'
  • @Grant - 是的,我现在明白了。好更新。很高兴你得到了解决方案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
相关资源
最近更新 更多