2011-09-23 48 views
1

使用LINQ多期的和值我有以下示例数据表:如何比较和VB.Net

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 

而现在的用户应该能够比较多个时段。在这个例子中,用户选择了两个时期:1.1.2010 - 31.12.2010和1.1.2011 - 31.12.2011。这个例子的结果应该是:

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

由于您已知道列数,因此可以按客户和产品对数据进行分组,然后从分组中获取条件总和,并且它将生成所得查询的不同列。 Plz看看下面的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;} 
} 
0

看一看 http://msdn.microsoft.com/en-us/vbasic/bb737908

具体地, '的GroupBy - 嵌套' 的例子。它显示了使用LINQ按'客户订单,首先按年,然后按月分组'。你的情况应该更直接,因为它只是日期范围。