连接多个group by元素并选择额外的列

时间:2014-09-26 02:13:01

标签: c# sql linq linq-to-sql

你能帮忙把它从sql转换成linq,我是linq的新手并且一直在尝试这个并且无法成功。如果这是可能的话,请告诉我?

SELECT max(Products.ProductID) as ProductID, Products.SKU, Products.Name, Products.RRP, Products.Price,
                     max(Products.FrontTall) as FrontTall,  
                     ProductsCategory.SortOrder, 
                     Products.ColorValue, 
                     max(Products.ColorImg) as ColorImg, 
                     Products.IsPrimary, 
                     Products.Visible 
                     FROM Products INNER JOIN ProductsCategory ON Products.ProductID = ProductsCategory.ProductID  
                     WHERE  (ProductsCategory.CategoryID =  5 ) AND (Products.Visible = 1) AND (Products.Inactive = 0) AND (Products.Deleted = 0 or Products.Deleted is null)  
                    GROUP BY SKU, Products.Name, RRP, Price, ColorValue, ProductsCategory.SortOrder, IsPrimary, Visible

这就是我正在尝试的

 var products = (from p in db.Products
                            join cp in db.ProductsCategories on p.ProductID equals cp.ProductID
                            where cp.CategoryID == catId && p.Visible == true && p.Inactive == false && (p.Deleted == null || p.Deleted == false) 
                            group p by new { 
                                p.SKU,
                                p.Name,
                                p.RRP,
                                p.Price,
                                p.ColorValue,             
                                p.IsPrimary,
                                p.Visible,
                                cp.SortOrder
                            } into grouped
                            select new { 
                                ProductID,
                                FrontTall,
                                ColorImg,
                                SKU = grouped.Key.SKU,
                                Name = grouped.Key.Name,                               
                                RRP = grouped.Key.RRP,
                                Price = grouped.Key.Price,
                                ColorValue = grouped.Key.ColorValue,                               
                                IsPrimary = grouped.Key.IsPrimary,
                                Visible = grouped.Key.Visible,
                                SortOrder = grouped.Key.SortOrder
                            })
                         .OrderBy(x => x.SortOrder);

我需要获取ProductID,FrontTall和ColorImg字段值,而不包括

分组

提前致谢。 凝析

1 个答案:

答案 0 :(得分:0)

select new {ProductID = grouped.Max(x => x.ProductID)}