تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Goal: Average Rentals0:00

Let's move on to another example. This time, I'm back in the Sequelize database. And similar to the previous episode, let's imagine that we want to inspect the rentals table. But rather than grouping the total rentals per day, which we could do, instead, I want to determine the average number of rentals across all of the stores. So if somebody wanted a single number, what's the average number of rentals per day for our business? Well, as you may know, we probably need some kind of aggregate. We're familiar with count and sum, but there's also average.

Well, as you may know, we probably need some kind of aggregate. We're familiar with count and sum, but there's also average. And I'm betting that's what we want. So what do we want? The average number of rentals per day? Well, it sounds like I first need to figure out what's the total number of rentals per day. Okay. So we're going to select * from the rental table. But notice that for any given day, we have many rentals.

Count Rentals Per Day0:49

So we're going to select * from the rentals table. But notice that for any given day, we have many rentals. So for this example database, it looks like seven rentals for the day. So instead, I'm going to say, give me the total number of items from the rentals table grouped according to the day of the rental. So I'll just do date here. So to make this a little more clear, we could select that as the day, and then the count will be aliased to totalRentals, something like that, and then we will group everything according to the day. And there you go.

Compute Average via Subquery1:44

Okay. So now that I have this information here, the next step is to fetch the average number of rentals. So it sounds like this should be a subquery. Okay. Let's try it out. I know that I need the average number of total rentals, but how do I connect these two? Well, here's a little tip. As it turns out, any time you reference a table name, whether it's rental or any of these tables, you can alternatively substitute a subquery.

Alias the Derived Table2:06

As it turns out, any time you reference a table name, whether it's rental or any of these tables, you can alternatively substitute a subquery. So let's try that. From the results of this query. But now, if I give it a run, it still doesn't fail. Every derived table must have its own alias. So what's happening is we're trying to read something from a subquery, but there is no alias to pull from. Why don't we just call it rentals? And if I give it another run, there we go.

Round and Alias Result2:33

Why don't we just call it rentals? And if I give it another run, there we go. Finally, I want to round it up. So let's wrap this within a round call. The last step is we have that ugly signature. So let's alias it to averageRentals. And there's your number.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟