如何选择具有LINQ to SQL中的多列分组的MAX ID的记录

问题描述 投票:0回答:1

我需要选择特定列的最后一条记录。我有以下记录

WarehouseId | ItemId | SubItemId | DeliveryGroupId | Other Columns
     1      |   1    |     1     |        1        |      ...
     1      |   1    |     1     |        2        |      ...
     1      |   1    |     1     |        3        |      ...
     1      |   1    |     2     |        1        |      ...
     1      |   1    |     2     |        2        |      ...
     1      |   2    |     1     |        1        |      ...

然后,我只想为每个WarehouseId | ItemId | SubItemId选择MAX(DeliveryGroupId)。结果应为:

WarehouseId | ItemId | SubItemId | DeliveryGroupId | Other Columns
     1      |   1    |     1     |        3        |      ...
     1      |   1    |     2     |        2        |      ...
     1      |   2    |     1     |        1        |      ...

在SQL中,这很简单:

SELECT *
FROM [dbo].[tblOrderDeliveryGroup] t1
WHERE [DeliveryGroupId] IN
(
    SELECT MAX([DeliveryGroupId])
    FROM [dbo].[tblOrderDeliveryGroup] t2
    WHERE (t1.[WarehouseId] = t2.[WarehouseId]) AND (t1.[ItemId] = t2.[ItemId]) AND (t1.[SubItemId] = t2.[SubItemId])
    GROUP BY [WarehouseId], [ItemId], [SubItemId]
);

问题是,我如何将该SQL语句转换为LINQ-to-SQL?

谢谢

c# linq-to-sql entity-framework-6
1个回答
0
投票

尝试以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("WarehouseId", typeof(int));
            dt.Columns.Add("ItemId", typeof(int));
            dt.Columns.Add("SubItemId", typeof(int));
            dt.Columns.Add("DeliveryGroupId", typeof(int));

            dt.Rows.Add(new object[] {1,1,1,1});
            dt.Rows.Add(new object[] {1,1,1,2});
            dt.Rows.Add(new object[] {1,1,1,3});
            dt.Rows.Add(new object[] {1,1,2,1});
            dt.Rows.Add(new object[] {1,1,2,2});
            dt.Rows.Add(new object[] {1,2,1,1});

            DataTable dt2 = dt.AsEnumerable()
                .OrderByDescending(x => x.Field<int>("DeliveryGroupId"))
                .GroupBy(x => new { warehouse = x.Field<int>("WarehouseId"), item = x.Field<int>("ItemId"), subitem = x.Field<int>("SubItemId")})
                .Select(x => x.FirstOrDefault())
                .CopyToDataTable();

        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.