c# – 如何在LINQ-to-SQL中生成SQL COUNT(*)OVER(PARTITION BY {ColumnName})?

是否可以使用LINQ-to-SQL查询表达式或延迟可执行的方法链生成以下SQL查询?

数据结构

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

最佳答案 试试这个:

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