我有以下示例数据表:
Value1 Value2 Customer Product Date
100 50 1000 100 1.8.2010
50 20 1000 101 5.1.2010
200 60 1000 100 6.2.2011
180 100 1001 100 7.3.2010
500 700 1000 100 1.1.2010
300 300 1001 100 4.4.2011
250 600 1000 100 3.3.2011
现在用户应该可以比较多个时段。在这个例子中,用户选择了两个时期:2010年1月1日至2010年12月31日和2011年12月31日至2011年12月31日。示例的结果应该是:
Customer Product SumValue1Period1 SumValue2Period1 SumValue1Period2 SumValue2Period2
1000 100 600 750 450 660
1000 101 50 20 0 0
1001 100 300 100 300 300
我该怎么做?
答案 0 :(得分:0)
看一看 http://msdn.microsoft.com/en-us/vbasic/bb737908
具体来说,就是“ GroupBy - 嵌套”示例。它显示了使用LINQ按“客户的订单,按年,然后按月分组”。你的情况应该更直接,因为它只是日期范围。
答案 1 :(得分:0)
由于您已知列数,因此您可以按客户和产品对数据进行分组,然后从分组中获取条件总和,它将生成查询的不同列。
请查看以下LinqPad程序。对不起,我不熟悉VB.Net所以我用C#编写了它,但你会得到一个公平的想法:
void Main()
{
var Period1Start = new DateTime(2010,1,1);
var Period1End = new DateTime(2010,12,31);
var Period2Start = new DateTime(2011,1,1);
var Period2End = new DateTime(2011,12,31);
List<Item> lst = new List<Item>
{
new Item{ Value1 = 100, Value2 = 50, Customer = 1000, Product = 100 , Date = new DateTime(2010,8,1)},
new Item{ Value1 = 50, Value2 = 20, Customer = 1000, Product = 101 , Date = new DateTime(2010,5,1)},
new Item{ Value1 = 200, Value2 = 60, Customer = 1000, Product = 100 , Date = new DateTime(2011,2,6)},
new Item{ Value1 = 180, Value2 = 100, Customer = 1001, Product = 100 , Date = new DateTime(2010,7,3)},
new Item{ Value1 = 500, Value2 = 700, Customer = 1000, Product = 100 , Date = new DateTime(2010,1,1)},
new Item{ Value1 = 300, Value2 = 300, Customer = 1001, Product = 100 , Date = new DateTime(2011,4,4)},
new Item{ Value1 = 250, Value2 = 600, Customer = 1000, Product = 100 , Date = new DateTime(2011,3,3)}
};
var grp = lst.GroupBy(x=>new{x.Customer, x.Product}).
Select(y=> new
{
Customer = y.Key.Customer,
Product = y.Key.Product,
SumValue1Period1 = y.Where(x=>x.Date >= Period1Start && x.Date<= Period1End).Sum(p=>p.Value1),
SumValue2Period1 = y.Where(x=>x.Date >= Period1Start && x.Date<= Period1End).Sum(p=>p.Value2),
SumValue1Period2 = y.Where(x=>x.Date >= Period2Start && x.Date<= Period2End).Sum(p=>p.Value1),
SumValue2Period2 = y.Where(x=>x.Date >= Period2Start && x.Date<= Period2End).Sum(p=>p.Value2)
});
Console.WriteLine(grp);
}
// Define other methods and classes here
public class Item
{
public int Value1{get;set;}
public int Value2{get;set;}
public int Customer{get;set;}
public int Product{get;set;}
public DateTime Date{get;set;}
}