我有以下 SQL 查询,我想将其重写到 LINQ 中:
SELECT gp.Name
, r.DateOfRace
, ISNULL(SUM(rr.Points), 0) AS Points
FROM Races r
INNER JOIN GrandPrix gp
ON r.GrandPrixId = gp.GrandPrixId
LEFT JOIN Predictions p
ON p.RaceId = r.RaceId
AND p.AdditionalUserInformationId = 2
LEFT JOIN RaceResults rr
ON p.DriverId = rr.DriverId
AND p.FinishPosition = rr.FinishPosition
AND p.RaceId = rr.RaceId
WHERE r.Season = 2010
GROUP BY gp.Name
, p.RaceId
, r.DateOfRace
这就是我得到的,当它还在工作的时候:
from races in Races
join grandprix in GrandPrixes
on races.GrandPrixId equals grandprix.GrandPrixId
from Predictions in Predictions.Where(v => v.RaceId == races.RaceId).DefaultIfEmpty()
select new
{
DateOfRace = races.DateOfRace,
GrandPrix = grandprix.Name,
}
当我走得更远时,事情就出错了 - 例如,我无法正确获取 AND p.AdditionalUserInformationId = 2。
希望有人能帮忙!
请您参考如下方法:
您可以执行以下操作:
join p in Predictions
on new { p.RaceId, p.AdditionalUserInformationId } =
new { r.RaceId, AdditionalUserInformationId = 2 } into ps
from p in ps.DefaultIfEmpty()
join rr in RaceResults
on new { p.DriverId, p.RaceId, p.FinishPosition } =
new { rr.DriverId, rr.RaceId, rr.FinishPosition } into rrs
from rr in rrs.DefaultIfEmpty()
您可以使用 C# 的功能在结构上比较匿名类型。创建的两个匿名类型具有相同的属性,这使它们成为同一类的实例。然后可以比较这些实例。
