[英]How to create Linq2Sql query, calculating aggregates?
Is there any way to create Linq2SQL query, that will be translated to this: 有什么方法可以创建Linq2SQL查询,该查询将转换为此:
SELECT COUNT(*) as totalCount ,
SUM(v.field1) AS totalfield1,
....
SUM(v.<fieldN>) AS total<fieldN>
FROM [dbo].[SomeTable] v
I have found soluthion with DataObjects.NET 我已经用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: 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];
You can try something like 您可以尝试类似
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);
but your solution of using fake key and then enumerating seems much better. 但是您使用假密钥然后枚举的解决方案似乎要好得多。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.