如何将此SQL转换为LINQ? (按人气排序)

时间:2012-01-26 14:47:34

标签: c# sql linq entity-framework

编辑:基于下面的一篇文章,我想出了如何编写它。答案就在这篇文章的最后。

我有一个商店......其中一个下拉菜单允许您按受欢迎程度对产品进行分类(最常购买的商品,首先显示)。

我知道如何在SQL中编写它,但我在LINQ中失败了。有人可以为我翻译吗?希望如果我看到足够的这些例子,我会自己做得更好......

我只是想带回所有物品,但按顺序排列。您可以通过查看itemId在“OrderDetails”表中出现的次数来判断哪些是最受欢迎的。

select i.*
from items i
left outer join (
    select od.itemid, ct = COUNT(1)
    from orderdetails od
        join orders o on od.orderid = o.orderid
    where o.ordersubmitteddate is not null
    group by od.itemid
    ) pop on pop.itemid = i.itemid
order by pop.ct desc, i.name

------下面回答-------

这是答案,我首先编写一个查询以确定我想要显示哪些“项目”...然后我写了第二个查询来订购....

var items = db.Items.Where("STUFF");

items = from i in items
        join pop in (
            from od in db.OrderDetails
            where od.Order.OrderSubmittedDate != null
            group od by od.ItemId into g
            select new { ItemId = g.Key, Ct = g.Count() }
        ) on i.ItemId equals pop.ItemId into pop_join
        from x in pop_join.DefaultIfEmpty()
        orderby x.Ct descending, i.Name
        select i;

2 个答案:

答案 0 :(得分:1)

好吧,你可以试试

var pop =   from od in context.OrderDetail
            join o in context.Order on od.OrderId equals o.OrderId
            where o.OrderSubmittedDate != null
            group by od.ItemId into g
            select new { ItemId = g.Key, Count = g.Count() };

var query = from p in pop
            join i in items on p.ItemId equals i.ItemId into j
            from x in j.DefaultIfEmpty()
            order by x.Count descending, i.Name;

这绝对可以让你朝着正确的方向前进,但我不能保证这甚至可以编译。这个想法是你可以在LINQ to SQL中嵌套查询。

答案 1 :(得分:0)

from i in Items
orderby i.ItemOrderDetails.Count(o=>o.Order.OrderSubmittedDate!=null) descending
select i

如果您在商品和订单详情之间没有关系,那么您可以这样做:

from i in Items
orderby (OrderDetails.Count(d=>d.ItemId==i.Id && d.Order.OrderSubmittedDate!=null)) descending
select i

如果您希望使用尽可能多的查询语法,您也可以这样表达:

from i in Items
let OrdersSubmitted= 
( from d in OrderDetails
  where d.ItemId == i.Id 
  where d.Order.OrderSubmittedDate != null
  select d)
orderby OrdersSubmitted.Count() descending 
select i

let语句非常便于生成更容易阅读的linq语句。