【问题标题】:Querying highest value by keys from database通过数据库中的键查询最大值
【发布时间】:2012-11-05 17:08:49
【问题描述】:

附下表:

+-------------+-----------+---------+
|  Parent_ID  |  Item_ID  |  Count  |
+-------------+-----------+---------+
|      1      |     1     |    1    |
|      1      |     1     |    5    |
|      1      |     1     |    4    |
|      1      |     2     |    7    |
|      1      |     2     |    2    |
|      2      |     1     |    2    |
|      2      |     1     |    3    |
|      2      |     2     |    2    |
|      2      |     2     |    4    |
+-------------+-----------+---------+

我想获得给定 Parent_IDItem_ID 的最高可用计数,如下所示:

+-------------+-----------+---------+
|  Parent_ID  |  Item_ID  |  Count  |
+-------------+-----------+---------+
|      1      |     1     |    5    |
|      1      |     2     |    7    |
|      2      |     1     |    3    |
|      2      |     2     |    4    |
+-------------+-----------+---------+

我将如何在 C# 中使用 LINQ/SQL 执行此操作?例如,我希望父 id 为 1 的项目计数最高。这将类似于:

int parentId = 1;
var counts = from c in database.Items where parentId == c.parentId 
//this gets all counts from items for parent id 1, but I am just looking
//for the highest count per item for parent id 1

【问题讨论】:

    标签: c# .net sql linq


    【解决方案1】:
    SELECT Parent_ID, Item_ID, MAX(Count)
    FROM ...
    GROUP BY Parent_Id, Item_ID
    

    【讨论】:

      【解决方案2】:
      select parent_id, 
             item_id, 
             max(count) as count
      from your_table
      group by parent_id, item_id
      

      【讨论】:

        【解决方案3】:

        要按多个字段分组,您可以使用匿名对象进行分组:

        var counts = from item in database.Items
                     group item by new { item.ParentId, item.ItemId } into itemGroup
                     select new Item()
                            {
                                ParentId = itemGroup.Key.ParentId,
                                ItemId = itemGroup.Key.ItemId,
                                Count = itemGroup.Max(x => x.Count)
                            };
        

        【讨论】:

          【解决方案4】:

          使用 LINQ2SQL 我想你想要这样的东西:

          var counts = database.Items.GroupBy(p => p.parentId).Max(p => p.Key);
          

          【讨论】:

          • 他想对 parentID 和 childID(不仅仅是 parentID)进行分组,尽管这与此代码相比没有显着变化。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-07
          相关资源
          最近更新 更多