【问题标题】:LINQ Query using 3 tables to get grouped data使用 3 个表获取分组数据的 LINQ 查询
【发布时间】:2012-11-20 11:22:24
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用导航属性加入您的课程吗?

标签: linq dataset


【解决方案1】:

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

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();

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多