2011-09-23 155 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按'客戶訂單,首先按年,然後按月分組'。你的情況應該更直接,因爲它只是日期範圍。