我正试图为这个滚动平均SQL语句编写等效的LINQ,但我正在努力解决如何使用相同的表(BulbSales
)两次别名为x
和y
。
你能帮忙吗?
SELECT x.Id, AVG(y.Sales) moving_average
FROM BulbSales x, BulbSales y
WHERE x.Id>=6 AND x.Id BETWEEN y.Id AND y.Id+5
GROUP BY x.Id
ORDER BY x.Id
如果这是LINQ to SQL,您可以尝试:
var query = from x in context.BulbSales
from y in context.BulbSales
where x.Id >= 6 && x.Id >= y.Id && x.Id <= (y.Id + 5)
group new { x.Id, y.Sales } by x.Id into g
orderby g.Key
select new { Id = g.Key, Average = g.Average(tuple => tuple.Sales) };
生成SQL:
SELECT [t2].[Id], [t2].[value] AS [Average]
FROM (
SELECT AVG([t1].[Sales]) AS [value], [t0].[Id]
FROM [dbo].[BulbSales] AS [t0], [dbo].[BulbSales] AS [t1]
WHERE ([t0].[Id] >= @p0) AND ([t0].[Id] >= [t1].[Id]) AND ([t0].[Id] <= ([t1].[Id] + @p1))
GROUP BY [t0].[Id]
) AS [t2]
ORDER BY [t2].[Id]