C# – How to generate SQL COUNT(*) OVER (PARTITION BY {ColumnName}) in LINQ-to-SQL

.net-3.5c++linqlinq-to-sql

Is it possible to generate the following SQL query by using LINQ-to-SQL query expression or method chains which is defer-executable?

Data Structure

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

Expected Result

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

Best Solution

Try this:

        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);

I didn't test the above but you can check my original code in case I got something wrong in the rewrite:

        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);