简体   繁体   English

LINQ OrderBy通过联接表中的记录计数

[英]LINQ OrderBy Count of Records in a Joined Table

I'm having trouble translating the following tSQL to LINQ to SQL in C#. 我在将以下tSQL转换为C#中的LINQ to SQL时遇到问题。 Any help would be much appreciated: 任何帮助将非常感激:

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

It's the ordering by the COUNT of a JOINED table that's throwing me for a loop. 这是由JOINED表的COUNT排序导致的循环。

Here's what I have so far (with no orderby): 这是我到目前为止(没有订单):

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;

Thanks for any help! 谢谢你的帮助!

You need to execute a group by if you want the count 如果需要计数,则需要执行一个分组

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

I'll assume you actually want the count for each group in the projection. 我假设您实际上想要投影中每个组的计数。

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

See comment to question. 请参阅评论评论。

How to do "order by" in linq -> 如何在Linq中执行“排序依据”->

If you have 如果你有

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

you can do 你可以做

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

to sort it in place. 将它排序到位。

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

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