通过查询帮助LINQ to SQL组

时间:2011-05-11 00:23:03

标签: linq-to-sql

LINQ group by syntax让我很困惑。在TSQL中,我可以选择多个列,并且只能按其中一个列进行分组。使用LINQ,它让我按照我想要使用的所有列进行组合。

如何将此TSQL转换为LINQ?

      SELECT         MAX(Item.itemID) AS Expr1, MAX(Item.title) AS Expr2,
 SUM(OrderDetail.quantity) AS Qty, MAX([Order].dateCreated) AS Expr3
        FROM            Payment INNER JOIN
                        [Order] ON Payment.ID = [Order].orderID INNER JOIN
                        OrderDetail ON [Order].orderID = OrderDetail.orderID INNER JOIN
                        Item ON OrderDetail.itemID = Item.itemID
        WHERE           ([Order].dateCreated >= '4 / 15 / 2011 12:00:00 AM') 
                        AND ([Order].dateCreated <= '4/15/2011 11:59:00 PM')
        GROUP BY Item.itemID
        ORDER BY Expr2



 var q = from p in db.Payments
                        join o in db.Orders on p.ID equals o.paymentID
                        join od in db.OrderDetails on o.orderID equals od.orderID
                        join i in db.Items on od.itemID equals i.itemID into j1
                        from j2 in j1
                        where o.dateCreated >= new DateTime(2011, 4, 15)
                        group j2 by j2.itemID into g
                        select new
                        {
                            g.Key 
                        };

1 个答案:

答案 0 :(得分:1)

var query =
    from p in db.Payments
    join o in db.Orders
        on p.ID equals o.orderID
    join od in db.OrderDetails
        on o.orderID equals od.orderID
    join i in db.Items
        on od.itemID equals i.itemID
    where o.OrderDate.Date == new DateTime(2011, 4, 15)
    group new { i.itemID, i.title, od.quantity, o.dateCreated }
        by i.itemID into g
    let Expr1 = g.Max(x => x.itemID)
    let Expr2 = g.Max(x => x.title)
    let Qty = g.Sum(x => x.quantity)
    let Expr3 = g.Max(x => x.dateCreated)
    orderby Expr2
    select new { Expr1, Expr2, Qty, Expr3 };