
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 method to group data and perform aggregations on the groups.
is a method that groups data based on the values of one or more columns. Once the data is grouped, we can perform aggregations on the groups. It is incredibly useful when we want to calculate statistics for different groups in our data.
You need at least two pieces of information to use the method:
So let's see how we can use the method in practice.
Imagine, like before, we want the average price of our in every . In a previous lesson, we calculated the average price for all products, and even the average price of products in a specific . Using the method, we can calculate the average price of products in every in a single query all at once.
Here's how we can do it:
//
const averagePriceInCategory = await prisma.product.groupBy({
by: ["category"], // pick the column to group
_avg: {
price: true,
},
});
And we'll get an output like this:
//
[
{
category: "Electronics",
_avg: {
price: 200,
},
},
{
category: "Books",
_avg: {
price: 20,
},
},
{
category: "Clothing",
_avg: {
price: 50,
},
},
];
We can even run multiple aggregations on the groups. For example, let's say we want to calculate the average price and the total number of products in each . We can do it like this:
//
const averagePriceAndCountInCategory = await prisma.product.groupBy({
by: ["category"],
_avg: {
price: true,
},
_count: {
category: true,
},
});
And we'll get an output like this:
//
[
{
category: "Electronics",
_avg: {
price: 200,
},
_count: {
category: 2,
},
},
{
category: "Books",
_avg: {
price: 20,
},
_count: {
category: 3,
},
},
{
category: "Clothing",
_avg: {
price: 50,
},
_count: {
category: 1,
},
},
];
As you can see, the method is a powerful tool that allows us to group data and perform aggregations on the groups. It is incredibly useful when we want to calculate statistics for different groups in our data.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.