2011-05-16 91 views
0

任何人都可以帮助我与下面的SQL的等效LINQ查询? 我是新来的LINQ等效的LINQ to SQL查询

Select * From Students_History SH 
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1 
group by SH1.StudentId) 

这是我曾尝试

var q = 
    from h in Students_History 
    where h.Active=1 
    group h by h.StudentId into g 
    select new 
    { 
     StudentID = g.Key, 
     LatestModified = g.Max (x => x.ModifiedAt) 
    } 

这LINQ查询不给我正确的结果,并以某种方式主动= 1被忽略

我有我的Students_History表中有大约十几个字段,我希望所有这些字段不仅仅是studentId和ModifiedAt。

回答

0

试试这个:

var q = 
    from hg in Students_History 
    group hg by hg.StudentId into g 
    join h in Students_History on g.Key equals h.StudentId 
    where h.Active == 1 && h.ModifiedAt == g.Max(x => x.ModifiedAt) 
    select new 
    { 
     StudentID = h.StudentId, 
     LatestModified = h.ModifiedAt 
    } 
+0

就像一个魅力。我只需要替换h.Active == true – Sonali 2011-05-16 23:49:01

0

您需要使用==运算符进行比较。

+0

我已经尝试过==好 – Sonali 2011-05-16 23:01:40

+0

主动= 1是不是唯一的问题。我也在寻找正确的查询。 – Sonali 2011-05-16 23:05:47