甚至可以使用LINQ編寫以下查詢嗎?我整天都在戰鬥,:(使用Group By和Max將SQL轉換爲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
甚至可以使用LINQ編寫以下查詢嗎?我整天都在戰鬥,:(使用Group By和Max將SQL轉換爲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
解決方法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]
我希望它能幫助你
試試這個:
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();
謝謝,這對我有點幫助。但我必須在第一個表中的Group By子句中包含2個字段,並從第二個表中拉出另一個項目,我不得不稍微修改以在LINQ中運行正常。 – bhishan