如何在linq中加入三个表与子表和

时间:2014-08-26 04:57:23

标签: c# linq linq-to-sql

我有三个表,四分之一,一个月和项目

QuarterTable

  QuarterId    Status    Amount

MonthTable

  MonthId  QuarterId  Amount

  ItemId  MonthId  ProductId  Amount   DateTime

产品项目金额应按月计算。 我想在linq中查询结果如下:

Quarter1 => { Month1 => { items from month1 }, 
              Month2 => { items from month2 }, 
              Month3=> { items from month3 }
            }

Quarter2 => { Month4 => { items from month4 },
              Month5 => { items from month5 }, 
              Month6 => { items from month6 }
            }

Quarter3 => { Month7 => { items from month7 },
              Month8 { items from month8 }, 
              Month9 { items from month9 }
            }

这是我尝试过的LINQ:

from MonthTable in MonthTable 
select new
       { 
         a = MonthTable, 
         b = (from Items in Items 
              group Items by new { Items.MonthId, Items.ProductId, Items.DateTime.Month, Items.Amount } 
              into newGroup 
              where newGroup.Key.MonthId == MonthTable.MonthId 
              select new { b = newGroup.Sum(x => x.Amount), ProductId = newGroup.ProductId })
       }

我是linq的新手,任何人都可以帮助我如何做到这一点

1 个答案:

答案 0 :(得分:0)

我可以看到您的Table设计存在一些DB Schema设计问题。不过,以下内容对您有所帮助。我没有测试过。但应该工作正常。

var JoinedCollection = from qt in QuarterTables
                       join mt in MonthTables on qt.QuarterId equals mt.QuarterId
                       join it in Items on mt.MonthId equals it.MonthId
                       select new
                       {
                           Quarter = qt.QuarterId,
                           Month = mt.MonthId,
                           Item = it.ItemId,
                           Amount = it.Amount
                       };

var GroupedCollection = JoinedCollection.GroupBy(jc => new
{
    jc.Quarter,
    jc.Month
});

var SummedCollection = GroupedCollection.Select(gc => new
{
    Quarter = gc.Key.Quarter,
    Month = gc.Key.Month,
    Total = gc.ToList().Sum(a => a.Amount)
});

或合并为

var SummedCollection = from qt in QuarterTables
                       join mt in MonthTables on qt.QuarterId equals mt.QuarterId
                       join it in Items on mt.MonthId equals it.MonthId
                       group new
                       {
                           Quarter = qt.QuarterId,
                           Month = mt.MonthId,
                           Item = it.ItemId,
                           Amount = it.Amount
                       }
                       by new
                       {
                           qt.QuarterId,
                           mt.MonthId
                       } into gc
                       select new
                       {
                           Quarter = gc.Key.QuarterId,
                           Month = gc.Key.MonthId,
                           Total = gc.ToList().Sum(a => a.Amount)
                       };