Exercise 2: Prolific, Popular Authors — Possible Solution =========================================================== const groups = await prisma.post.groupBy({ by: ["authorId"], where: { published: true }, // rows: published posts only _count: { _all: true }, _avg: { viewCount: true }, having: { authorId: { _count: { gte: 3 } }, // groups: at least 3 posts viewCount: { _avg: { gt: 50 } }, // groups: average above 50 }, orderBy: { _avg: { viewCount: "desc" } }, }); const users = await prisma.user.findMany({ where: { id: { in: groups.map((g) => g.authorId) } }, select: { id: true, name: true }, }); const names = new Map(users.map((u) => [u.id, u.name])); const result = groups.map((g) => ({ author: names.get(g.authorId) ?? "(unknown)", posts: g._count._all, avgViews: g._avg.viewCount, })); console.table(result); Example output: ┌─────────┬─────────┬───────┬──────────┐ │ (index) │ author │ posts │ avgViews │ ├─────────┼─────────┼───────┼──────────┤ │ 0 │ 'Grace' │ 4 │ 171.25 │ │ 1 │ 'Ada' │ 9 │ 91.1 │ └─────────┴─────────┴───────┴──────────┘ WHY THIS WORKS AS AN ANSWER ------------------------------ "Published" is a condition on individual posts, so it goes in where. "At least 3 posts" and "average above 50" are conditions on whole groups, so they go in having — both filter on aggregate values, which is what having allows. groupBy can't include the author, so names come from one extra findMany with an "in" filter: two queries in total no matter how many authors qualify.