2012-04-01 58 views
2

我有一個數據表與關係數據結構,我需要總結子節點到它們的父節點的所有一直到子總計關係的數據表

我已附加2個圖像的頂部父(NULL父ID)這表明原始表和其他與預期結果

original data in datatable

expected results

乾杯

+4

您正在使用哪些DBMS?語法各不相同,特別是對於像這樣的更高級的查詢。 – McGarnagle 2012-04-01 03:12:01

+0

我想在數據表中做一些這樣的數據,而不是在數據庫中。 – trailerman 2012-04-01 03:36:38

+0

爲你的問題添加正確的標籤,是不是關於C#和LINQ而不是SQL? – arturro 2012-04-01 04:15:17

回答

1

我已經採取了一種模擬數據的方法,因爲它們可能已經通過某些ORM實現了數據庫,即包含數據和子集合的類。再加上一些「商業邏輯」來計算所需的數字。所以你可以選擇一種數據庫方式以及內存方式。

在Linqpad:

void Main() 
{ 
    var data = new[] 
    { 
     new Record { Id = 1, ParentId = null, Qty = 1, Cost = 0.0m }, 
     new Record { Id = 2, ParentId = 1, Qty = 2, Cost = 0.0m }, 
     new Record { Id = 3, ParentId = 1, Qty = 3, Cost = 0.0m }, 
     new Record { Id = 4, ParentId = 2, Qty = 4, Cost = 0.0m }, 
     new Record { Id = 5, ParentId = 3, Qty = 5, Cost = 0.0m }, 
     new Record { Id = 6, ParentId = 2, Qty = 6, Cost = 1.7m }, 
     new Record { Id = 7, ParentId = 4, Qty = 7, Cost = 1.8m }, 
     new Record { Id = 8, ParentId = 5, Qty = 8, Cost = 1.9m }, 
     new Record { Id = 9, ParentId = 5, Qty = 9, Cost = 2.0m }, 
    }.ToList(); 

    // Mimic ORM's job: 
    data.ForEach(d => d.ChildRecords = 
     data.Where(c => c.ParentId == d.Id).ToList()); 

    data.Select(d => new { d.Id, d.Cost, d.TotalCost }).Dump(); 
} 

class Record 
{ 
    public int Id { get; set; } 
    public int? ParentId { get; set; } 
    public int Qty { get; set; } 

    private decimal _cost = 0m; 
    public decimal Cost 
    { 
     get { return this._cost + this.ChildRecords.Sum(cr => cr.TotalCost); } 
     set { this._cost = value; } 
    } 

    public decimal TotalCost 
    { 
     get { return this.Qty * this.Cost; } 
    } 

    public ICollection<Record> ChildRecords; 
} 

結果:

Id Cost TotalCost 
1 619.2 619.2 
2 60.6 121.2 
3 166  498 
4 12.6 50.4 
5 33.2 166 
6 1.7  10.2 
7 1.8  12.6 
8 1.9  15.2 
9 2  18 

的優化可以應用一些記憶化,即讓成本屬性存儲在它的私有成員變量的getter的結果。