汇总其表在join子句中但不在group子句中的字段

问题描述 投票:0回答:1

我想将此查询转换为Linq。我离开了加入BLTb到BMTb和CbTb。我没有在group by子句中使用BLTb。我无法将此查询转换为Linq,因为我无法求和BLTb.IsAprv。我只可以对表在linq中的group by子句中的字段求和。

有人可以告诉我如何将以下查询转换为Linq。

注意:“ BLTb.BLCod”不是表“ BLTb”的PK。“ BMTb.Id”不是表“ BMTb”的PK]

SELECT     BMTb.BCod, CBTb.CmCod, 
CASE WHEN   
    SUM(CASE WHEN ISNULL(BMTb.IsAprv, 0) = 0 THEN 1 ELSE 0 END) +
    SUM(CASE WHEN BLTb.IsAprv = 0 THEN 1 ELSE 0 END)
    > 0 then 0 else 1 end AS IsAprv
FROM BMTb 
INNER JOIN CBTb ON BMTb.CBCod = CBTb.CBCod 
LEFT OUTER JOIN BLTb ON BMTb.Id = BLTb.BLCod
GROUP BY  BCod 

Linq:

var BMTb = (from m in db.BMTbs.AsQueryable()
                            select new
                            {
                                isAprove=m.IsAprv==null?1:m.IsAprv==false?1:0,
                                m.CBCod,
                               m.IsAprv,
                               m.BCod,
                               m.Id
                            }
                            );
        var BLTb = (from l in db.BLTbs.AsQueryable()
                            select new
                            {
                                l.BMCod,
                               isAprove= l.IsAprv==false?1:0

                            }
                            );


        var AproveCB = (from m in BMTb.AsQueryable()
                           join c in db.CBTbs.AsQueryable() on m.CBCod equals c.CBCod
                           join l in BLTb.AsQueryable() on m.Id equals l.BMCod into lL
                           from lLeft in lL.DefaultIfEmpty()
                           group new { m, c } by new {m.BCod,c. CmCod, }
                           into grp
                           select new
                           {
                               sum1=grp.Sum(gp=>gp.m.isAprove)/*+grp.Sum(gp => gp.isAprove) */> 0?0:1,
                               BCod=grp.Key.BCod,
                               CmCod=grp.Key.CmCod,


                           }
                           );
sql-server entity-framework linq group-by left-join
1个回答
0
投票

这是将SQL直接转换为Linq:

var ans = from b in BMTb
          join c in CBTb on b.CBCod equals c.CBCod
          join l in BLTb on b.Id equals l.Id into lj
          from l in lj.DefaultIfEmpty()
          group new { bIsAprv = b.IsAprv, c.CmCod, lIsAprv = l.IsAprv } by b.BCod into bclg
          select new {
              BCod = bclg.Key,
              bclg.First().CmCod,
              IsAprv = (bclg.Sum(bcl => bcl.bIsAprv == null ? 1 : 0)+bclg.Sum(bcl => bcl.lIsAprv == 0 ? 1 : 0) > 0) ? 0 : 1
          };

我用First()从组中抽出一个CmCod,我认为SQL不合法。

© www.soinside.com 2019 - 2024. All rights reserved.