将INNER JOIN,GROUP BY,ORDER BY和MAX()的SQL查询转换为LINQ

时间:2017-03-21 21:25:09

标签: c# sql linq

我目前正在尝试转换以下SQL查询:

SELECT ref.pa_nbr, MAX(ins.ins_id)
FROM referral ref
INNER JOIN ins i ON ref.referral_nbr = i.referral_nbr
INNER JOIN pm p ON i.pm_nbr = p.pm_nbr AND p.pm_group = 2
WHERE ref.pat_nbr = @pat_nbr
GROUP BY ref.pat_nbr
ORDER BY ref.pat_nbr

进入LINQ表达式。我已经尝试了几次但没有收到正确的结果。最新的尝试可以在以下内容中看到:

var medicaidNumber = 
    (from referral in context.REFERRALs
     join ins in context.INSs on referral.REFERRAL_NBR equals ins.REFERRAL_NBR
     join pm in context.PMs on ins.PM_NBR equals pm.PM_NBR
     where referral.P_NBR == patid && pm.PM_GROUP == 2
     orderby referral.PAT_NBR
     group referral by referral.PAT_NBR).FirstOrDefault();

有人可以看看我在做什么,看看是否还有其他方法可以解决这个问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

你必须分组成一个变量,然后你可以进行最大聚合。

from referral in context.REFERRALs
join ins in context.INSs on referral.REFERRAL_NBR equals ins.REFERRAL_NBR
join pm in context.PMs on ins.PM_NBR equals pm.PM_NBR
where referral.P_NBR == patid && pm.PM_GROUP == 2
orderby referral.PAT_NBR
group ins.INS_Id by referral.PAT_NBR into grp
select new { PAT_NBR = grp.Key, MaxINSId = grp.Max() };