2012-04-10 132 views
3

你好,我试图找出如何写在LINQ的SQL语句,但我无法找到一个方法来做到这一点的时刻,这是SQL命令:LINQ GROUP BY和MAX()

SELECT cs.Site_Name, MAX(ed.EffectiveDate_Date) 
FROM [WAPMaster].[Factsheets].[EffectiveDate] ed, 
[WAPMaster].[Configuration].[Site] cs 
WHERE cs.Site_Id = ed.EffectiveDate_SiteId 
GROUP BY cs.Site_Name 

请问有人可以帮我理解linq语法吗?由于

**我想这个到目前为止(感谢levanlevi)

var test = (from e in this._wapDatabase.EffectiveDates 
      join c in this._wapDatabase.Sites 
      on c.Site_Id equals e.EffectiveDate_SiteId 
      group e by c.Site_Name into r 
      select new 
      { 
       r.Key.SiteName, 
       EffectiveDate = r.Max(d => d.EffectiveDate_Date) 
      }); 

但我发现了以下错误:

http://i.stack.imgur.com/AkJ5V.png

+2

只要注意:没有任何翻译*快*和*已经工作* SQL查询到LINQ。只需使用SQL。 Linq *不会更好*。 – Tigran 2012-04-10 09:14:07

回答

10
SELECT cs.Site_Name , 
     MAX(ed.EffectiveDate_Date) 
FROM [WAPMaster].[Factsheets].[EffectiveDate] ed , 
     [WAPMaster].[Configuration].[Site] cs 
WHERE cs.Site_Id = ed.EffectiveDate_SiteId 
GROUP BY cs.Site_Name 



from e in WAPMaster.Factsheets.EffectiveDate 
join c in WAPMaster.Configuration.Site 
on c.Site_Id equals e.EffectiveDate_SiteId 
group e by c.Site_Name into r 
select new { SiteName = r.Key, EffectiveDate = r.Max(d=>d.EffectiveDate_Date)} 
+0

感谢看起来真的很接近,它告诉我“无法解析连接方法”,你知道它为什么可以吗? – 2012-04-10 09:39:04

+0

http://i.stack.imgur.com/Z9o9E.png这是我得到的错误。 – 2012-04-10 09:45:45

+0

你使用实体框架吗? LinqToSql类之间有连接吗? – levi 2012-04-10 10:09:01

1
var test = (from effectiveDates in this._wapDatabase.EffectiveDates       
      from sites in this._wapDatabase.Sites       
      where sites.Site_Id = effectiveDates.EffectiveDate_SiteId 
        group effectiveDates by sites.Site_Id into g       
      select new { siteId = g.key , effectiveDate = g.max(ed => ed.EffectiveDate_Date)});