gpt4 book ai didi

sql-server - EF Core Linq 中子查询的总和

转载 作者:行者123 更新时间:2023-12-03 03:12:04 28 4
gpt4 key购买 nike

我想通过在求和查询中输入子查询来获得结果。

当我写入 Sql 时,以下代码有效。

但是在 EF 上,如何在顶部添加另一个选择?

SQL

这段代码可以工作。

select 
sum (data.rate)
from
(
SELECT
t1.Id,
(c.rate /
(SELECT COUNT(1) FROM [table4] AS [t4] WHERE ([t4].[FKId] = p1.Id))) as rate
FROM [table1] AS [t1]
INNER JOIN [table2] AS [t2] ON ([t1].[FKId] = [t2].[Id])
INNER JOIN [table3] AS [t3] ON ([t1].[FKId] = [t3].[Id]))
as data

C#

var data = await (
????
from t1 in ctx.table1
join t2 in ctx.table2 on new { t1.FKId} equals new { FKId = t2.Id}
join t3 in ctx.table3 on new { t1.FKId} equals new { FKId = t3.Id}
select new
{
rate = t3.Rate /
(from t4 in ctx.table4
where t4.FKId == t2.Id
select t4.Id)
.Count())
})
.SumAsync(sm => (double?)sm.rate ?? 0);

此 C# 代码无法正常工作。

错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

最佳答案

this answer ,EF Core 3.0仍然无法处理这种情况(!)。

但是,您可以在没有子查询的情况下转换查询(有效地,使用SelectMany)并且它应该可以工作:

var ans = await (from t1 in ctx.table1
join t2 in ctx.table2 on t1.FKId equals t2.Id
join t3 in ctx.table3 on t1.FKId equals t3.Id
from t4 in ctx.table4
where t4.FkId == t2.Id
group t4.Id by new { t3.rate, t2.Id } into t2g
select t2g.Key.rate / t2g.Count()
)
.SumAsync();

关于sql-server - EF Core Linq 中子查询的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59178347/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com