Linq 到 SQL 转换...无法添加第二个 COUNT
Linq to SQL conversion...unable to add second COUNT
我正在尝试将我的 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()
。
如果您需要 table 结构和示例数据,请参阅 。
以您的查询为基础,您需要包含 s 的组,以便在非空时进行计数(我还删除了分组键周围不必要的匿名对象):
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)
}
但是,与其翻译 SQL,我可能会利用 LINQ 的组连接来稍微不同地处理查询:
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
但取决于您的数据库引擎,可能无关紧要。
我正在尝试将我的 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()
。
如果您需要 table 结构和示例数据,请参阅
以您的查询为基础,您需要包含 s 的组,以便在非空时进行计数(我还删除了分组键周围不必要的匿名对象):
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)
}
但是,与其翻译 SQL,我可能会利用 LINQ 的组连接来稍微不同地处理查询:
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
但取决于您的数据库引擎,可能无关紧要。