Linq to SQL转换...无法添加第二个COUNT

时间:2018-04-14 15:04:54

标签: linq linq-to-sql

我正在尝试将我的SQL语句转换为Linq语句,但我不确定如何将第二个COUNT添加到它。这是我的SQL语句

SELECT l.Campus_Name, Labs = COUNT(*), LabsWithSubnets = COUNT(s.Lab_Space_Id)
FROM vw_Lab_Space l
LEFT JOIN vw_Subnet s on l.Lab_Space_Id = s.Lab_Space_Id
GROUP BY l.Campus_Name
ORDER BY 1

这是我到目前为止的LINQ声明:

from l in Vw_Lab_Space
from s in Vw_Subnet
            .Where(s => s.Lab_Space_Id == l.Lab_Space_Id)
            .DefaultIfEmpty()   // <=- triggers the LEFT JOIN
group l by new { l.Campus_Name } into g
orderby g.Key.Campus_Name
select new {
    Campus_Name = g.Key.Campus_Name,
    Labs = g.Count()
}

所以除了LabsWithSubnets部分之外我还有其他所有内容。我只是不确定如何添加它,因为我不能在select语句中执行s.Lab_Space_id.Count()

如果您需要表格结构和样本数据,请参阅Need help creating an OUTER JOIN to count spaces

1 个答案:

答案 0 :(得分:0)

使用您的查询作为基础,您需要组包含s,以便您可以在非null时计数(我还删除了分组键周围不必要的匿名对象):

from l in Vw_Lab_Space
from s in Vw_Subnet
            .Where(s => s.Lab_Space_Id == l.Lab_Space_Id)
            .DefaultIfEmpty()   // <=- triggers the LEFT JOIN
group new { l, s } by l.Campus_Name into g
orderby g.Key
select new {
    Campus_Name = g.Key,
    Labs = g.Count(),
    LabsWithSubnets = g.Count(ls => ls.s != null)
}

但是,我可能会利用LINQ的组连接来稍微区别地处理查询,而不是翻译SQL:

var ans = from l in Vw_Lab_Space
          join s in Vw_Subnet on l.Lab_Space_Id equals s.Lab_Space_Id into sj
          group new { l, sj } by ls.Campus_Name into lsjg
          select new {
              Campus_Name = lsjg.Key,
              NumLabs = lsjg.Count(),
              LabsWithSubnets = lsjg.Sum(lsj => lsj.sj.Count())
          };

PS即使在您的查询中,我也会使用join ... from ... DefaultIfEmpty而不是from ... from .. 。where但是根据您的数据库引擎,可能无关紧要。