0

使用下表:

+-------------+-----------+---------+
|  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_ID和的最高可用计数Item_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
4

4 回答 4

1
SELECT Parent_ID, Item_ID, MAX(Count)
FROM ...
GROUP BY Parent_Id, Item_ID
于 2012-11-05T17:10:55.960 回答
1
select parent_id, 
       item_id, 
       max(count) as count
from your_table
group by parent_id, item_id
于 2012-11-05T17:11:00.203 回答
0

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

var counts = database.Items.GroupBy(p => p.parentId).Max(p => p.Key);
于 2012-11-05T17:16:03.890 回答
0

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

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)
                    };
于 2012-11-05T17:38:57.810 回答