LINQ OrderBy连接表中的记录数

时间:2011-12-02 01:23:22

标签: c# sql linq

我在使用C#将以下tSQL转换为LINQ to SQL时遇到问题。任何帮助将不胜感激:

SELECT P.Name
FROM Product P
    INNER JOIN OrderItems OI ON P.productID = OI.productID
        INNER JOIN Orders O ON OI.orderID = O.orderId
WHERE P.Active = 1 AND O.Status > 2
ORDER BY count(OI.orderID) DESC

这是一个JOINED表的COUNT排序,它让我循环。

这是我到目前为止(没有订单):

from p in CRM.tProducts
    join oi in CRM.tOrderItems on p.prodID equals oi.prodID
    join o in CRM.tOrders on oi.orderID equals o.orderID
where o.status > 1 && p.active == true
select p;

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

如果你想要计数

,你需要执行一个组
SELECT P.Name
FROM Product P
    INNER JOIN OrderItems OI ON P.productID = OI.productID
        INNER JOIN Orders O ON OI.orderID = O.orderId
WHERE P.Active = 1 AND O.Status > 2
GROUP BY P.Name
ORDER BY count(*) DESC

我假设您实际上想要投影中每个组的计数。

from p in CRM.tProducts
    join oi in CRM.tOrderItems on p.prodID equals oi.prodID
    join o in CRM.tOrders on oi.orderID equals o.orderID
where o.status > 1 && p.active == true
group p by p.Name into nameGroup
orderby nameGroup.Count()
select new { Name = nameGroup.Key, Count = nameGroup.Count() };

答案 1 :(得分:0)

见评论问题。

如何在linq中执行“order by” - >

如果你有

  var alist = ....  select new { prd = p, ord =  o };

你可以做到

  alist.sort( (a, b) => a.ord.CompareTo(b.ord) );

将其排序。