使用Group By和Max将SQL转换为LINQ

时间:2016-04-14 22:48:44

标签: c# sql linq lambda

甚至可以使用LINQ编写以下查询吗?我整天都在战斗,:(

select * from ProductGroup pg 
Inner join (
    select max(DateShipped) as ShipDate
        , ProductId
    from Lot lt
    group by ProductId) lte
    on pg.ProductId = lte.ProductId

2 个答案:

答案 0 :(得分:1)

<强>解决方法1

我使用LinqToSQL在LinqPad上测试了这个。

var data = from lt in  Lots            
           group lt by lt.ProductId into grp
           join pg in ProductGroups on grp.Key equals pg.ProductId
           select new { pg.ProductId,pg.ProductName,ShipDate =grp.Max (g => g.ShipDate)};

data.Dump();

它产生了这个SQL(几乎就像你的sql,只是表的顺序被切换)

SELECT [t2].[ProductId], [t2].[ProductName], [t1].[value] AS [ShipDate]
FROM (
    SELECT MAX([t0].[ShipDate]) AS [value], [t0].[ProductId]
    FROM [Lot] AS [t0]
    GROUP BY [t0].[ProductId]
    ) AS [t1]
INNER JOIN [ProductGroup] AS [t2] ON [t1].[ProductId] = [t2].[ProductId]

<强>溶液2

这是一种强制相关子查询的方法,该子查询产生的结果与您想要的相同但没有连接/组

var data = from pg in ProductGroups
           let sd = Lots.Where (l => l.ProductId == pg.ProductId ).Max(l => l.ShipDate )
           select new { pg.ProductId,pg.ProductName,ShipDate =sd};

    data.Dump();

它生成了这个SQL

SELECT [t0].[ProductId], [t0].[ProductName], (
    SELECT MAX([t1].[ShipDate])
    FROM [Lot] AS [t1]
    WHERE [t1].[ProductId] = [t0].[ProductId]
    ) AS [sd]
FROM [ProductGroup] AS [t0]

我希望它能帮到你

答案 1 :(得分:0)

试试这个:

var result = (from pg in ProductGroup
                join lte in
                (
                    from lt in Lot
                    group lt by lt.ProductId into gr
                    select new
                    {
                        ProductId = gr.Key,
                        ShipDate = gr.Max(x => x.DateShipped)
                    }
                )
                on pg.ProductId equals lte.ProductId
                select new
                {
                    ID = pg.ProductId,
                    MaxShipDate = lte.ShipDate
                }).ToList();