【问题标题】:How to create Linq2Sql query, calculating aggregates?如何创建 Linq2Sql 查询,计算聚合?
【发布时间】:2014-09-16 21:40:47
【问题描述】:

有什么方法可以创建 Linq2SQL 查询,会被翻译成这样:

SELECT  COUNT(*) as totalCount ,
 SUM(v.field1) AS totalfield1,
....
 SUM(v.<fieldN>) AS total<fieldN>
FROM    [dbo].[SomeTable] v

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    你可以试试

    var query = from p in SalesOrderDetails 
             group p by p.ProductID into g
              select  new
              {id =  g.Key, Count = g.Count(), Sum = g.Sum(p => p.OrderQty)};   
    
    Console.Write(query);
    

    但是您使用假密钥然后枚举的解决方案似乎要好得多。

    var query = from p in SalesOrderDetails 
             group p by p.ProductID into g
            select  new
      {id =  g.Key, FalseKey = 1, Count = g.Count(), Sum = g.Sum(p => p.OrderQty) };
    
    //Console.Write(query);
    var result = from q in query
                      group q by q.FalseKey into c
                      select new { summation = c.Sum(q => q.Sum)};
    
    Console.Write(result);
    

    【讨论】:

      【解决方案2】:

      我找到了 DataObjects.NET 的解决方案

      var query =  
          from product in Query.All<Product>()
          where product.ProductName.Contains("a")
          select new {Product = product, FakeKey = 0} into i
          group i.Product.UnitPrice by i.FakeKey into g
          select new { Count = g.Count(), Price = g.Sum() };
      
        var result = query.AsEnumerable().Single();
      

      SQL:

      SELECT Count_big(*)         AS [column1], 
             SUM([a].[UnitPrice]) AS [column2] 
      FROM   (SELECT [b].[ProductId], 
                     [b].[TypeId], 
                     [b].[ProductName], 
                     [b].[Seller], 
                     [b].[Category.Id], 
                     [b].[ProductType], 
                     [b].[UnitPrice], 
                     [b].[UnitsInStock], 
                     [b].[UnitsOnOrder], 
                     [b].[ReorderLevel], 
                     [b].[QuantityPerUnit], 
                     0 AS [column] 
              FROM   [dbo].[Products] [b] 
              WHERE  ( [b].[ProductName] LIKE '%a%' )) [a] 
      GROUP  BY [a].[column];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        相关资源
        最近更新 更多