多重GROUP BY和LINQ总和 [英] Multiple group by and Sum LINQ
本文介绍了多重GROUP BY和LINQ总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个产品销售表,看起来像这样:
saleDate督促数量
09年10月22日肥皂10
09年9月22日05丸
09年9月25日06肥皂
09年9月25日15丸
我需要每月金额为最后的表是这样的:
saleDate督促数量
10/09肥皂10
09/09肥皂06
09/09丸20
我能做到这一点使用LINQ?
解决方案
变种产品=新[] {
新的{SaleDate =新日期时间(2009,10,22),产品=肥皂,数量= 10}
新的{SaleDate =新的DateTime(2009,09,22),产品=丸,数量= 5}
新的{SaleDate =新日期时间(2009,09,25),产品=肥皂,数量= 6},
新的{SaleDate =新日期时间(2009,09,25),产品=丸,数量= 15}
};
VAR总结=从产品
p令k =新的
{
//试试这个,如果你需要一个日期字段
//页。 SaleDate.Date.AddDays(-1 * p.SaleDate.Day - 1)
月= p.SaleDate.ToString(MM / YY),
产品= p.Product
}
群p用k入T
选择新的
{
月= t.Key.Month,
产品= t.Key.Product,
数量= t.Sum(p => p.Quantity)
};
的foreach(在汇总VAR项)
Console.WriteLine(项目);
// {月= 10/09,产品=香皂,数量= 10}
// {月= 09/09,产品=药片,数量= 20}
// {月= 09/09,产品=香皂,数量= 6}
I have a products sales table that looks like this:
saleDate prod qty
10/22/09 soap 10
09/22/09 pills 05
09/25/09 soap 06
09/25/09 pills 15
I need to make the SUM of each MONTH so the final table would look like this:
saleDate prod qty
10/09 soap 10
09/09 soap 06
09/09 pills 20
Can I do this with LINQ?
解决方案
var products = new[] {
new {SaleDate = new DateTime(2009,10,22), Product = "Soap", Quantity = 10},
new {SaleDate = new DateTime(2009,09,22), Product = "Pills", Quantity = 5},
new {SaleDate = new DateTime(2009,09,25), Product = "Soap", Quantity = 6},
new {SaleDate = new DateTime(2009,09,25), Product = "Pills", Quantity = 15}
};
var summary = from p in products
let k = new
{
//try this if you need a date field
// p.SaleDate.Date.AddDays(-1 *p.SaleDate.Day - 1)
Month = p.SaleDate.ToString("MM/yy"),
Product = p.Product
}
group p by k into t
select new
{
Month = t.Key.Month,
Product = t.Key.Product,
Qty = t.Sum(p => p.Quantity)
};
foreach (var item in summary)
Console.WriteLine(item);
//{ Month = 10/09, Product = Soap, Qty = 10 }
//{ Month = 09/09, Product = Pills, Qty = 20 }
//{ Month = 09/09, Product = Soap, Qty = 6 }
这篇关于多重GROUP BY和LINQ总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文