这是我的SQL查询,我想转换:
SELECT TOP (10)
t1.ProductName, t2.ProductName,
COUNT(DISTINCT t1.OrderId) AS num_orders
FROM
Reports t1
JOIN
Reports t2 ON t1.OrderId = t2.OrderId
AND t1.ProductId < t2.ProductId
GROUP BY
t1.ProductName, t2.ProductName
ORDER BY
num_orders DESC
可以看到,在"on"中,orderId
必须相同,并且其中一个的productId
必须小于另一个。
这是我到目前为止所取得的成就(非常不完整):
var reportData = await (from t1 in this.Context.Reports
join t2 in this.Context.Reports
on t1.OrderIdequals t2.OrderId
where t1.ProductId < t2.ProductId
into GroupedData
orderby GroupedData.Key
select new
{
GroupedData
}).ToListAsync();
如果我将表达式与"one_answers"在"on"我试着在单独的地方做,但仍然不起作用。
选择也是不完整的,因为我还没有设法让上面所有的代码工作,所以不要给它任何重要性。
我最接近的是让它为我工作,我得到了同样的错误,这个人得到:我怎么能使用Linq表达式在EF Core 3.1中加入GroupBy
这是我用来搜索信息的页面,但它没有显示我要找的东西:https://learn.microsoft.com/en-us/ef/core/querying/complex-query-operators
我也使用过Linq和这个SQL到Linq的存储库,但我不能让他们工作,我是一个大三学生:(
有人可以帮助我或建议我在哪里寻找信息?
试试这个
var reportData = (from t1 in Context.Reports
join t2 in Context.Reports on t1.OrderId equals t2.OrderId
select new { t1 = t1, t2 = t2 }
).Where(x => x.t1.ProductId < x.t2.ProductId)
.GroupBy(x => new { t1Id = x.t1.ProductId, t2Id = x.t2.ProductId })
.Select(x => new { t1ProductName = x.First().t1.ProductName, x.First().t2.ProductName, num_Orders = x.Select(y => y.t1.OrderId).Distinct().Count()})
.OrderByDescending(x => x.num_Orders);
try this,
var result = (from t1 in Reports
join t2 in Reports on t1.OrderId equals t2.OrderId
where t1.ProductId < t2.ProductId
group new { t1, t2 } by new { t1.ProductName, t2.ProductName } into g
let numOrders = g.Select(x => x.t1.OrderId).Distinct().Count()
orderby numOrders descending
select new
{
ProductName1 = g.Key.ProductName,
ProductName2 = g.Key.ProductName2,
NumOrders = numOrders
}).Take(10);