【发布时间】:2026-02-03 23:30:02
【问题描述】:
我有一张有作者的桌子,还有一张有书籍的桌子。它们在本书的authorID 中连接。我想根据流派计算作者的平均年龄。它看起来像这样:
- 书籍:ID、书名、流派、作者 ID
- 作者:authorID、姓名、年龄
我想获得按类型分组的平均年龄。但是数据库中有同一作者的书籍。我想在这个查询中只计算一次。我有这个,但如果作者相同,这会再次计算它们:
var query = from books in this.bookRepository.ReadAll()
join authors in this.authorRepository.ReadAll() on books.writerId equals authors.authorId
select new
{
books.booktype,
authors.age,
authors.authorId,
};
var result = from g in query
group g by g.booktype into groupedTypes
select new AverageOfWritersAgeInGenreModel
{
Genre = groupedTypes.Key,
Age = groupedTypes.Average(x => x.age).Value,
};
【问题讨论】:
-
您首先查询给每个属性一个名称。发件人:books.booktype,收件人:bookType = books.booktype,
标签: c# sql .net database entity-framework