我要转换的 SQL 查询是:
select p.PhoneNumber_Id, p.State, p.Created
from PhoneNumberServiceItems p
join PhoneNumbers on p.PhoneNumber_Id = PhoneNumbers.Id
inner join (
select PhoneNumber_Id, max(Created) as MaxDate
from PhoneNumberServiceItems
group by PhoneNumber_Id
) tm on p.PhoneNumber_Id = tm.PhoneNumber_Id and p.Created = tm.MaxDate
where PhoneNumbers.NumberRangeId = {Id}
我最终得到的 LINQ 代码如下,但这不起作用:
var res =
from serviceItems in _db.PhoneNumberServiceItems
join nums in _db.PhoneNumbers on serviceItems.PhoneNumber_Id equals nums.Id
where nums.NumberRangeId == id
join serviceGroup in (from ps in _db.PhoneNumberServiceItems
group ps by ps.PhoneNumber_Id into numGroup
//join tm in _db.PhoneNumbers on psg.FirstOrDefault().PhoneNumber_Id equals tm.Id
select new
{
NumId = numGroup.FirstOrDefault().PhoneNumber_Id,
MaxDate = numGroup.Max(i => i.Created)
}) on new { PNId = serviceItems.PhoneNumber_Id, serviceCreated = serviceItems.Created } equals new { PNId = serviceGroup.NumId, serviceCreated = serviceGroup.MaxDate }
select new
{
State = serviceItems.State,
NumId = serviceGroup.NumId,
Created = serviceGroup.MaxDate
};
我知道我的 LINQ 是错误的,但我无法指出我在做什么不同。任何帮助,将不胜感激。
编辑:这是从 LINQ 生成的已编译 SQL
SELECT
[Extent1].[State] AS [State],
[Project4].[C1] AS [C1],
[Project4].[C2] AS [C2]
FROM [dbo].[PhoneNumberServiceItems] AS [Extent1]
INNER JOIN [dbo].[PhoneNumbers] AS [Extent2] ON [Extent1].[PhoneNumber_Id] = [Extent2].[Id]
INNER JOIN (SELECT
[Project3].[C1] AS [C1],
(SELECT
MAX([Extent5].[Created]) AS [A1]
FROM [dbo].[PhoneNumberServiceItems] AS [Extent5]
WHERE [Project3].[PhoneNumber_Id] = [Extent5].[PhoneNumber_Id]) AS [C2]
RISEBY
慕村9548890
海绵宝宝撒
相关分类