在linq中加入2表和第2组字段

时间:2016-03-31 06:32:27

标签: c# sql linq

我有一个非常简单的SQL

SELECT s.shop_code
             ,SUM(im.amt)      sum_amt
             ,s.cell_no#1      shop_cell
       FROM   tb_sn_so_wt_mst  im
             ,tb_cm_shop_inf   s 
       WHERE  im.shop_code   = s.shop_code
GROUP BY s.shop_code, s.cell_no#1)

然后我尝试编码linq

var listResult = from warrantyMaster in listWarrantyMasters2.Records
                                          join shopInfo in listShopInfos
                                          on warrantyMaster.ShopCode equals shopInfo.ShopCode

我不知道按商店代码分组和单元格no和sum atm,任何人都可以帮我解决这个问题

2 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

 var results = from warrantyMaster in listWarrantyMasters2.Records
                  from shopInfo in listShopInfos
                       .Where(mapping => mapping.ShopCode == warrantyMaster.ShopCode )
                       .select new 
                       { 
                            ShopCode = warrantyMaster.ShopCode,
                            ATM = listWarrantyMasters2.ATM,
                            ShellNo = shopInfo.ShellNo
                       }
                       .GroupBy(x=> new { x.ShopCode, x.ShellNo })
                       .Select(x=> 
                       new{ 
                             ShopCode = x.Key.ShopCode,
                             ShellNo = x.Key.ShellNo,
                             SumATM = x.Sum(item=>item.ATM)
                       });

答案 1 :(得分:1)

此处解释了带有一些示例的语法组group clause (C# Reference)和相关链接。

这是您的SQL查询的直接翻译(当然,由于您没有提供您的课程,因此我只能猜测字段名称):

var query = from im in listWarrantyMasters2.Records
            join s in listShopInfos
            on im.ShopCode equals s.ShopCode
            group im by new { s.ShopCode, s.CellNo } into g
            select new
            {
                g.Key.ShopCode,
                g.Key.CellNo,
                SumAmt = g.Sum(e => e.Amt)
            };