简体   繁体   English

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

[英]Convert SQL query with INNER JOINs, GROUP BY, ORDER BY, and MAX() to LINQ

I am currently trying to convert the following SQL query: 我目前正在尝试转换以下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

into a LINQ expression. 成为LINQ表达式。 I have tried several times but have not received the correct results. 我已经尝试了几次,但没有收到正确的结果。 The latest attempt can be seen in the following: 可以在下面看到最新的尝试:

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();

Could someone take a look at what I am doing and see if there's another way to go about this? 有人可以看看我在做什么,看看是否还有另一种方法可以解决这个问题? Any help will be appreciated. 任何帮助将不胜感激。

You have to group into a variable that you can then do the max aggregation on. 您必须将变量分组,然后可以对其进行最大聚合。

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() };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM