2016-03-03 243 views
0

我尝试使用Lambda表达式进行复杂查询(而不是我)。我有我想要“翻译”到Lambda的SQL。在Lambda表达式中使用Max,Group By,Join和Where

SELECT MAX((SUBSTRING(tbp.dt,4,4)+SUBSTRING(tbp.dt,2,2)+SUBSTRING(tbp.dt,1,2))) as Dt, 
tb._n, tbp.number, tbp.dsc 
FROM TB_A tb 
JOIN TB_B_C tbp ON tbp.number = tb.number 
WHERE tbp.rec = 0 AND tbp.processing = 0 AND tb._n != '' AND tbp.error = 0 
GROUP BY tb._n, tbp.number, tbp.dsc 

到现在为止我有这样的Lambda表达式:

var results = db.a 
      .Join(db.b_c, proc => proc.number, andam => andam.number, (proc, andam) => new { proc, andam }) 
      .Where(d => d.proc._n != "" && d.andam.rec == false && d.andam.processing == false && d.andam.error) 
      .ToList(); 

我要如何完成我的选择有相同的结果SQL查询?如果可能,你可以解释在将查询翻译成Lambda时如何正确思考?

非常感谢。

+2

你问我们你错过了什么,先告诉我们它有什么问题。 –

+0

这也有助于查看您的实体。例如,如果你有一个从'a'到'b_c'的导航属性,那么你不需要进行连接。 – juharr

+0

@TimSchmelter谢谢!我改变了我提出问题的方式! –

回答

1

它通常是更容易查询语法来写

var results = from tb in db.a 
       join tbp in db.b_c on tb.number equals tbp.number 
       where tbp.rec == 0 
        && tbp.processing == 0 
        && tb._n != string.Empty 
        && tbp.error == 0 
       group new {tb, tbp} by new {tb._n, tbp.number, tbp.dsc} into grp 
       select new 
       { 
        grp.Key._n, 
        grp.Key.number, 
        grp.Key.dsc, 
        Dt = grp.Max(x => x.tbp.dt.Substring(4,4) 
            + x.tbp.dt.Substring(2,2) 
            + x.tbp.dt.Substring(0,2)) 
       }; 
+0

非常感谢!有用! –

0

所有你需要做的是

1)GroupBySelect声明

2)添加到用GroupJoin代替Join

下面的例子是不相关的数据库模式...

选项1)

var results = ... 
      .GroupBy(x=> new {x.Field1, x.Field2, x.Field3}) 
      .Select(grp=>new 
      { 
       Key = grp.Key, 
       MaxVal = grp.Max(o=>o.Field1) 
      }); 

选项2)

var result = db_a.Where(x=>x.Field1==1 && x.Field2==0) 
      .GroupJoin(db_b.Where(x=>x.Field3==5), 
         a => a.PrimaryKey, 
         b => b.ForeignKey, 
         (a, b) => new 
          { 
           PK=a.PrimaryKey, 
           MaxVal=b.Max(o=>o.Field2) 
          }); 

来源:https://msdn.microsoft.com/en-us/library/bb534297%28v=vs.110%29.aspx