0

因此,我正在尝试获取城市列表以及每个城市中最畅销产品的名称。有 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();

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

4

1 回答 1

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();
于 2012-12-03T02:24:09.493 回答