
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, we will learn how to use the avg aggregate function to calculate the average of a field in a Prisma query.
We will use the avg function to calculate the average of the price field in the Product table.
In the previous lesson, we were able to use the aggregate function to count the number of records in a table.
is the only aggregate function that has it's own method attached to the Prisma table object- for all other aggregate functions, we need to use the method, or build them in the query.
Let's start by using the method to calculate the average price of all products in the Product table.
//
const avgPrice = await prisma.product.aggregate({
_avg: {
price: true,
},
});
We'd get an output similar to this:
//
{
"_avg": {
"price": 10.5
}
}
This takes all the prices in the Product table, adds them up, and divides by the number of records to get the average price.
Can you get the average price for all products in a specific category?
Use the where argument to filter the products by category. Then simply collect the average price like we did above.
//
const test = await prisma.product.aggregate({
where: {
category: "home",
},
_avg: {
price: true,
},
});
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.