2016-04-25 85 views
2

我有下面的SQL(MS-Sql 2014)語句可用。將sql(row_number和DENSE_RANK)轉換爲linq

如何將此SQL轉換爲LINQ?

我正在閱讀它,但只是把它放在那裏,以防我無法做到這一點。

 
select OriginalDocumentNumber ,FilterRound , p2_Reason , p2_FinalGrade , rowno , s_index , t_index 
      from (
        select * , 

        rowno=row_number() over (partition by OriginalDocumentNumber,FilterRound order by p2_FinalGrade desc) , 
        s_index = ROW_NUMBER() OVER(PARTITION BY FilterRound,OriginalDocumentNumber ORDER BY p2_FinalGrade), 
        t_index = DENSE_RANK() OVER (ORDER BY p2_FinalGrade) 
        from #TempDa 
       ) l 
      where 
      l.p2_FinalGrade in ('d','f') 
      and l.rowno = 1 
      and l.OriginalDocumentNumber = '590200054' 
      and l.p2_Reason = 'test' 
      and l.OriginalDocumentNumber+l.FilterRound not in (select OriginalDocumentNumber+FilterRound from #TempDa where p2_FinalGrade in ('a','b','c') 
      ) 

更新

List<string> validValues = new List<string>() { "A", "B", "C" }; 
        List<string> GradeReject = new List<string>() { "d", "f" }; 
        var tempDb = 
         res.GroupBy(p => new {p.OriginalDocumentNumber, p.FilterRound}) 
          .Select(grp => grp.OrderByDescending(g => g.p2_FinalGrade).FirstOrDefault()); 

        var temp = res.Where(r => validValues.Contains(r.p2_FinalGrade)).Select(r => r.OriginalDocumentNumber+r.FilterRound); 
        fds = tempDb.Where(r => GradeReject.Contains(r.p2_FinalGrade) && !temp.Contains(r.OriginalDocumentNumber + r.FilterRound)) 
        .Select(r => new DataAllProcessDetailModels() { FilterRound = r.FilterRound, OriginalDocumentNumber = r.OriginalDocumentNumber, DocumentNumber = r.DocumentNumber, LandDescription = r.LandDescription, DStatus = " " }).ToList(); 

非常感謝你。

回答

1

也許不是了,但是對於其他人誰有關穿越在此:

回答了關於如何做dense_rank更多的解釋:

implement dense rank with linq

回答這個特定問題:

var result = data.GroupBy(item => new { item.OriginalDocumentNumber, item.FilterRound }) 
    .OrderBy(@group => @group.First().p2_FinalGrade) 
    .AsEnumerable() 
    .Select((@group, groupIndex) => new 
    { 
     Items = @group.Select((item, index) => new { Item = item, Index = ++index }), 
     Rank = ++groupIndex 
    }) 
    .SelectMany(v => v.Items, (s, i) => new 
    { 
     Data = i.Item, 
     RankInGroup = i.Index, 
     DenseRank = s.Rank 
    }).ToList(); 

result.Where(item => item.Data.p2_FinalGrade == "d" || 
         item.Data.p2_FinalGrade == "f") 
     .Where(item => item.Data.OriginalDocumentNumber == "590200054").... 
+0

這是更高性能,因爲您使用分組,而其他Stackoverflow答案使用子選擇,導致更多的查詢。 –