【问题标题】:Linq to SQL using group By, and order by countLinq to SQL 使用 group By 和 order by count
【发布时间】:2011-04-18 06:14:30
【问题描述】:

这是mysql查询:

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

它的 LINQ to SQL 是什么。

【问题讨论】:

    标签: c# sql mysql linq


    【解决方案1】:

    应该是一组成:

    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 Resource 的示例

    【讨论】:

    • 感谢您的回复,但我无法访问此
    • 问题也要求订购,请参阅我的解决方案。
    【解决方案2】:

    试试这个:

    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 。但是这个查询不起作用,我该怎么办?
    • 请添加评论而不是添加答案。您必须向我展示您想到的 sql 查询,因为聚合函数可能无法实现您的要求。
    • 这是我的 SQL 查询:SELECT count(ProductVersion), ProductVersion , ProductID , SubProductID FROM [do-not-delete-accounts].[dbo].[Activation_Details] group by ProductVersion,ProductID,SubProductID按计数排序(ProductVersion);它的 Linq to sql 是什么。
    • 我已经用你的新问题更新了我的答案。如果这对您有好处,请将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多