我想在linq中執行一個左連接,它有一個date1> date2比較的sql,但無法弄清楚如何。這裏的SQL:Linq to SQL - 左加入>比較
select
rd.RouteDispatchID,
r.RouteNumber,
s.ShortDescription,
rd.DispatchDate,
rd.CreationDate,
e.FirstName,
e.LastName,
count(md.MachineDispatchID) NumMachines,
count(mdp.Pick) TotalPicks,
sum(mh.BillsToStacker) + sum(mh.BoxCash) TotalCash,
sum(mh.TubeCash) - sum(mh.CashOut) NetCoinsToTubes
from dbo.RouteDispatch rd
inner join dbo.Route r on rd.RouteID = r.RouteID
inner join dbo.Reference s on rd.StatusCodeReferenceID = s.ReferenceID
inner join dbo.Employee e on rd.CreatedByEmployeeID = e.EmployeeID
left join dbo.MachineDispatch md on rd.RouteDispatchID = md.RouteDispatchID and md.IsSelected = 1
left join dbo.MachineDispatchPick mdp on md.MachineDispatchID = mdp.MachineDispatchID
**left join dbo.MachineHistory mh on md.MachineID = mh.MachineID and mh.ReadDate > m.LastServiceDate**
group by rd.RouteDispatchID,
r.RouteNumber,
s.ShortDescription,
rd.DispatchDate,
rd.CreationDate,
e.FirstName,
e.LastName
我把粗體問題的左連接。下面是我對LINQ到目前爲止,但我已經離開了mh.ReadDate> m.LastServiceDate,因爲我不知道如何做到這一點:
var query = from rd in db.RouteDispatches
join r in db.Routes on rd.RouteID equals r.RouteID
join s in db.References on new { StatusCodeReferenceID = rd.StatusCodeReferenceID } equals new { StatusCodeReferenceID = s.ReferenceID }
join e in db.Employees on new { CreatedByEmployeeID = rd.CreatedByEmployeeID } equals new { CreatedByEmployeeID = e.EmployeeID }
join md in db.MachineDispatches
on new { rd.RouteDispatchID, IsSelected = true }
equals new { md.RouteDispatchID, IsSelected = md.IsSelected.Value } into md_join
from md in md_join.DefaultIfEmpty()
join mdp in db.MachineDispatchPicks on md.MachineDispatchID equals mdp.MachineDispatchID into mdp_join
from mdp in mdp_join.DefaultIfEmpty()
join mh in db.MachineHistories on md.MachineID equals mh.MachineID into mh_join
from mh in mh_join.DefaultIfEmpty()
group new { rd, r, s, e, md, mdp, mh } by new
{
rd.RouteDispatchID,
r.RouteNumber,
s.ShortDescription,
rd.DispatchDate,
rd.CreationDate,
e.FirstName,
e.LastName
} into g
select new RouteView
{
RouteDispatchID = g.Key.RouteDispatchID,
RouteNumber = g.Key.RouteNumber,
Status = g.Key.ShortDescription,
DispatchDate = g.Key.DispatchDate.Value,
CreatedDate = g.Key.CreationDate.Value,
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
NumMachines = g.Count(),
TotalPicks = g.Count(),
TotalCash = (g.Sum(p => p.mh.BillsToStacker.Value) + g.Sum(p => p.mh.BoxCash.Value)),
NetCoinsToTubes = (g.Sum(p => p.mh.TubeCash.Value) - g.Sum(p => p.mh.CashOut.Value))
};
任何人知道如何得到這個工作?
嘿列維, 我沒有看到您的查詢的WHERE子句。此外,它是一個左連接,所以我不能只說「哪裏mh.ReadDate> m.LastServiceDate」,因爲這會使其表現得像內連接而不是可選的左連接。 – Justin 2009-10-06 23:12:47