SQL Group By + MAX的LINQ / Lambda查询帮助?

时间:2011-10-21 07:32:18

标签: .net linq entity-framework

我想知道是否有人可以根据以下SQL查询帮助我使用lambda或LINQ查询(最好是lambda)。我尝试了一点但没有运气:(

SELECT TOP 1 MAX(cv.ProductID) as MaxProductID, MAX(ap.RegionAsLocationID) RegionID,
   COUNT(cv.ProductID) as ProductCount 
FROM CustomerVouchers cv
INNER JOIN Products p on p.id = cv.ProductID and p.status = 3
INNER JOIN APs ap on ap.id = p.apid
WHERE cv.Status = 1
GROUP BY cv.ProductID
ORDER BY ProductCount DESC

SQL返回如下结果:

MaxProductID | RegionID | ProductCount
123 | 16862 | 3

我在“最终结果”列之后,其中MAX()将是客户凭证记录,并且它的关系具有最多的产品ID。

感谢帮派。

1 个答案:

答案 0 :(得分:2)

假设ctx是您的实体模型,请使用以下内容。

 var result = from cv in ctx.CustomerVoucher
                         join p in ctx.Products on p.id equals cv.ProductID && p.status == 3
                         join ap in ctx.APs on ap.id equals prop.apid
                         where cv.status == 1
                         group cv by cv.ProductID into g
                         select new { MaxProductID = g.Max(cv => cv.ProductID), RegionID = g.max(ap => ap.RegionAsLocationID), ProductCount = g.Count(cv => cv.ProductID) };
相关问题