Linq to SQL使用Group By和Order By Count

14

这是MySQL查询:

SELECT count(PVersion), PVersion
  FROM [Products].[dbo].[Active_Details] 
group by PVersion 
order by count(PVersion);

它的 LINQ to SQL 将会是什么样子。

2个回答

18

试试这个:

var product = 
            from p in yourContext.Active_Details
            group p by p.PVersion into pgroup
            let count = pgroup.Count()
            orderby count
            select new { Count = count, PVersion = pgroup.Key };

SELECT count(ProductVersion), ProductVersion , ProductID , SubProductID 
FROM [do-not-delete-accounts].[dbo].[Activation_Details] 
group by ProductVersion,ProductID,SubProductID 
order by count(ProductVersion);

var query = 
            from p in yourContext.Activation_Details
            group p by new 
            { 
               ProductVersion = p.ProductVersion, 
               ProductID = p.ProductID,
               SubProductID = p.SubProductID 
            } 
            into pgroup
            let count = pgroup.Count()
            orderby count
            select new 
            { 
                Count = count, 
                ProductVersion = pgroup.Key.ProductVersion, 
                ProductID = pgroup.Key.ProductID,
                SubProductID = pgroup.Key.SubProductID  
            };

非常感谢。 还有一件事我想要, 我也想访问表的其他列,如PID、SPID。 但是这个查询不起作用,我该怎么办? - aayushi soni
请添加注释而不是添加答案。您必须向我展示您所考虑的SQL查询,因为您所要求的可能无法使用聚合函数实现。 - Bear Monkey
这是我的 SQL 查询:SELECT count(ProductVersion), ProductVersion, ProductID, SubProductID FROM [do-not-delete-accounts].[dbo].[Activation_Details] group by ProductVersion,ProductID,SubProductID order by count(ProductVersion); 它的 Linq to SQL 是什么? - aayushi soni
我已经更新了我的回答以回应你的新问题。如果这对你有帮助,请将其标记为已接受。 - Bear Monkey

7

应该将其分组:

var product = (
    from p in yourContext.Active_Details
    group p by p.PVersion into pgroup
    select new { VersionCount= pgroup.Count(), pgroup.Key }
).OrderBy(x=>x.VersionCount);

这里有一个MSDN资源,其中包含示例。


谢谢您的回复,但我无法访问这个。 - aayushi soni
问题要求按照顺序排序,可以看看我的解决方案。 - Bear Monkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接