LINQ查询使用3个表来获取分组数据

时间:2012-12-03 00:51:53

标签: linq dataset

所以我试图获得一个城市列表以及每个城市中销量最好的产品的名称。有3个表,我似乎无法正确分组并得到计数。

这是我到目前为止所做的:

var result9 = (from p in shop.Tb_Purchases
               join c in shop.Tb_PreferredCustomer on p.Cust_ID equals c.Cust_ID
               join ap in shop.Tb_AvailableProduct on p.Prod_ID equals ap.Prod_ID
               group ap by new { c.City, ap.Name } into g
               select new { City = g.Key.City, Name = g.Key.Name, NumOf = g.Count() }).ToList();

这给了我在每个城市销售的每件产品以及销售了多少产品,但是我只需要一个城市和一个销售最多的产品。

1 个答案:

答案 0 :(得分:0)

一种解决方案是按城市分组,然后在子查询中找到每个城市的最佳产品。

var result9 = (from p in shop.Tb_Purchases
               join c in shop.Tb_PreferredCustomer on p.Cust_ID equals c.Cust_ID
               join ap in shop.Tb_AvailableProduct on p.Prod_ID equals ap.Prod_ID
               group ap by c.City into g
               let largestProductGroup = g.GroupBy(x => x.Name)
                                          .OrderByDescending(x => x.Count())
                                          .First()
               select new
                      {
                         City = g.Key.City,
                         Name = largestProductGroup.Key.Name,
                         NumOf = largestProductGroup.Count()
                      }).ToList();