使用linq将3个表连接为1个表

bq8i3lrv  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(139)

我有一个主表,我想添加2列,这是从其他2个表的值的总和。
表1编码数量
表2代码数量
表3代码数量
我能够编写这段代码,它适用于前两个表,但我还想添加Tab3列,它应该是:Orders2=g.Sum(y=〉y.Qty3),但是在多次尝试之后,我就是不能加入第三个表。你能解释一下如何做到这一点吗?

var query =  
    from a in Tab1 
    join b in Tab2 
    on c.Cod equals b.Cod into temp 

    from t in temp.DefaultIfEmpty() 
    group t by new {a.Cod, a.Qty1} into g 

    select new 
    { 
        g.Key.Cod, 
        g.Key.Qty1, 
        Orders = g.Sum(x => x.Qty2) 
    };
ljsrvy3e

ljsrvy3e1#

这是一种方法。

var query =  
    from a in Tab1 
    join b in Tab2 on a.Cod equals b.Cod into tempB
    join c in Tab3 on a.Cod equals c.Cod into tempC

    from tB in tempB.DefaultIfEmpty()
    from tC in tempC.DefaultIfEmpty()

    group new { tB, tC } by new { a.Cod, a.Qty1 } into g

    select new 
    { 
        g.Key.Cod, 
        g.Key.Qty1, 
        Orders = g.Sum(x => x.tB?.Qty2 ?? 0),
        Orders2 = g.Sum(x => x.tC?.Qty3 ?? 0)
    };
9fkzdhlc

9fkzdhlc2#

好的,我自己解决了
我考虑创建另一个查询来调用第一个查询,这样我就可以添加另一个列summed。
还是谢谢你

var query1 =  
    from a in Tab1 
    join b in Tab2 on a.Cod equals b.Cod into tempB

    from tB in tempB.DefaultIfEmpty()

    group new { tB } by new { a.Cod, a.Qty1 } into g

    select new 
      { 
      cod = g.Key.Cod, 
      qty1 = g.Key.Qty1, 
      qty2 = g.Sum(x => x.tB.Qty2)
      };

var queryOK =  
    from c in query1 
    join d in Tab3 on c.cod equals d.Cod into tempC

    from tC in tempC.DefaultIfEmpty()

    group new { tC } by new { c.cod, c.qty1, c.qty2 } into k

    select new 
        { 
        cod = k.Key.cod, 
        qty1 = k.Key.qty1, 
        qty2 = k.Key.qty2,
        qty3 = k.Sum(y => y.tC.Qty3)
        };
    
dataGridView1.DataSource = query2.ToList();

相关问题