Linq得到max()分组

时间:2015-08-12 23:45:27

标签: c# linq

我有这个SQL查询:

declare @p_Date datetime 
set @p_Date = '01/01/2015'

select * 
from inv_hist
where Secuencia in (
    select max(Secuencia)
        from inv_hist
        where DatFechaDocumento <= @p_Date
            group by Bodega,NumIdConcepto
    )

如何在LINQ中编写此查询?

编辑:我整天都在想这件事。我不是linq的专家,其他类似的问题并不能解决我的问题。

1 个答案:

答案 0 :(得分:1)

试试这个:

var query = from x in invHistory
                    join y in
                            (
                                from z in invHistory
                                where z.PDate == "01/01/2015"
                                group z by new { z.Bodega, z.NumIDConcepto } into g
                                select new
                                       {
                                           NewSecuencia = g.Max(s => s.Secuencia) 
                                       }
                            ) 
                            on x.Secuencia equals y.NewSecuencia
                    select x;

如果你想要隐式风格,你可以这样做:

  var query2 = from x in invHistory
               from y in
                         (
                             from z in invHistory
                             where z.PDate == "01/01/2015"
                             group z by new { z.Bodega, z.NumIDConcepto } into g
                             select new
                             {
                                 NewSecuencia = g.Max(s => s.Secuencia)
                             }
                         )
               where 
                    x.Secuencia == y.NewSecuencia
               select x;
  

请注意,隐式样式连接语法(ANSI-89)不是标准,不推荐使用SQL Server 2005.