2010-06-23 82 views
4

是否可以通過使用延遲可執行的LINQ-to-SQL查詢表達式或方法鏈來生成以下SQL查詢?如何在LINQ-to-SQL中生成SQL COUNT(*)OVER(PARTITION BY {ColumnName})?

數據結構

alt text http://www.freeimagehosting.net/uploads/e062a48837.jpg

Select Distinct ClassRoomTitle, 
       Count(*) Over(Partition By ClassRoomNo) As [No Sessions Per Room], 
       TeacherName, 
       Count(*) Over(Partition By ClassRoomNo, TeacherName) As [No Sessions Per Teacher] From ClassRoom 

預期結果

alt text http://www.freeimagehosting.net/uploads/47a79fea8b.jpg

+0

CN你所得到的數據的波斯坦例子嗎? – Luiscencio 2010-06-23 21:44:33

+0

我剛編輯以包含預期結果。 – 2010-06-24 01:50:19

+0

只是編輯我的答案,以適應您的預期結果 – Luiscencio 2010-06-24 14:24:59

回答

1

試試這個:

 var vGroup = from p in ClassRoom 
        group p by new { p.ClassRoomNo, p.TeacherName } 
         into g 
         from i in g 
         select new 
         { 
          i.ClassRoomNo, 
          i.TeacherName, 
          i.ClassRoomTitle, 
          NoSessionsPerTeacher = g.Count() 
         }; 

     var pGroup = from p in vGroup 
        group p by new { p.ClassRoomNo } 
         into g 
         from i in g 
         select new 
         { 
          i.ClassRoomTitle, 
          NoSessionsPerRoom = g.Count(), 
          i.TeacherName, 
          i.NoSessionsPerTeacher 
         }; 

     var result = pGroup.OrderBy(p => p.ClassRoomNo).ThenBy(p => p.TeacherName); 

我沒有測試以上,但你可以的情況下,檢查我的原代碼,我得到了一些錯誤的改寫:

 var vGroup = from p in Products 
        group p by new { p.ProductId, p.VariantId } 
         into g 
         from i in g 
         select new 
         { 
          i.ProductId, 
          i.VariantId, 
          VariantCount = g.Count() 
         }; 

     var pGroup = from p in vGroup 
        group p by new { p.ProductId } 
         into g 
         from i in g 
         select new 
         { 
          i.ProductId, 
          ProductCount = g.Count(), 
          i.VariantId, 
          i.VariantCount 
         }; 

     var result = pGroup.OrderBy(p => p.ProductId).ThenBy(p => p.VariantId); 
1
var classRooms = from c in context.ClassRooms 
       group c by new {c.ClassRoomNo} into room 
       select new { 
        Title = room.First().ClassRoomTitle, 
        NoSessions = room.Count(), 
        Teachers = from cr in room 
           group cr by new {cr.TeacherName} into t 
           select new { 
            Teacher = t.Key, 
            NoSessions = t.Count() 
           } 
       }; 

比公佈的預期的結果更有條理一些,但我發現那會更好。

,如果你想回去非結構化您可以隨時使用的SelectMany:

var unstructured = classRooms 
    .SelectMany(c=> c.Teachers.Select(t=> new { 
     Title = c.Title, 
     SessionsPerRoom = c.NoSessions, 
     Teacher = t.Teacher, 
     SessionsPerTeacher = t.NoSessions 
    }); 
相關問題