2011-03-11 103 views
0

如果我有表是这样的:LINQ to SQL的最大问题

col1   col2 col3 col4 
apple  1  35 1  
apple  1  38 0  
apple  2  27 1  
orange  1  50 0  
orange  2  51 1  

我想通过组1的2列,最大COL3。最后我想得到:

apple  1  38 0 
apple  2  27 1  
orange  1  50 0 
orange  2  51 1 

什么是linq查询到这?

回答

0

第二次尝试。

var subquery = 
(from r in table group r by new { r.col1, r.col2} into results 
    select new 
    { 
     results.Key.col1, 
     results.Key.col2, 
     MaxCol3 = results.Max(i=>i.col3) 
    } 
) ; 


var query2 = 
    (from r in subquery1 
     select new 
     { 
     r.col1 , 
     r.col2 , 
     r.MaxCol3 , 
     col4 = (from x in subquery1 
      where r.col1 == x.col1 && r.col2 == x.col2 && x.col3 == r.MaxCol3 
      select x.col4).First() 
     } 
    ); 

我从来没有使用过这种语法,但我认为你也可以做类似的事情。

(from r in table group r by new { r.col1, r.col2} into results 
    let MaxCol3 = results.Max(i=>i.col3) 
    select new 
    { 
     results.Key.col1, 
     results.Key.col2, 
     MaxCol3 , 
     col4 = results.First(i=>i.col3 == MaxCol3).col4 
    } 
) ; 
+0

第四列呢? – 2011-03-11 12:52:25

+0

对不起,错过了那一点。 – sgmoore 2011-03-11 12:57:51

+0

已更新的答案。 – sgmoore 2011-03-11 13:29:26