I'm looking to provide the average rating of a restaurant along with the name of the owner

Currently, I am utilizing knex to craft queries for my express server. Within my database, I have two tables structured as follows:

My objective is to establish a join between the two tables using the "owner_id" foreign key. Subsequently, I aim to retrieve objects that include an "avg" key, indicating the average of all ratings by the respective owner, and an "owner_name" key denoting the name of the restaurant owner. Additionally, I need to organize the results by the owner's name.

This is the snippet I have incorporated into my knex query up to this point:

function listAverageRatingByOwner() {
 return knex("restaurants as r")
  .join("owners as o", "r.owner_id", "o.owner_id")
  .select("r.rating as avg", "o.owner_name")
  .orderBy("o.owner_name")
}

I have also experimented with the following approach:

return knex("restaurants as r")
        .join("owners as o" , "r.owner_id", "o.owner_id")
        .select("r.rating as avg", "o.owner_name")
        .groupBy("o.owner_name")
        .avg("r.rating")
        .orderBy("o.owner_name")

Although this implementation does return data, the owners are not grouped together by their name with the corresponding average rating for each.

This is the current data output I am receiving: enter image description here

However, my anticipated outcome is as follows:

{
  "data": [
    {
      "avg": 3.8200000000000003,
      "owner_name": "Amata Frenzel;"
    },
    {
      "avg": 2.25,
      "owner_name": "Curtice Grollmann"
    },
    {
      "avg": 2.45,
      "owner_name": "Daffy Furzer"
    }
  ]
}

I would greatly appreciate any assistance on how to properly group by owner_name along with the average rating for each owner. Thank you!

Below are the migrations for the two tables in my database:

Owners

Restaurants

Answer №1

It appears that you are receiving the exact results you requested. You have multiple restaurants, various owners, and are combining the two to extract the owner's name and rating.

Based on your description, it seems you want to group the data by the owner's name and calculate the average rating for each restaurant. To achieve this, you should explicitly use the average function on the ratings field and group the results by owner name as shown below:

return knex("restaurants as r")
        .join("owners as o" , "r.owner_id", "o.owner_id")
        .avg("r.rating as avg")
        .select("avg", "o.owner_name")
        .groupBy("o.owner_name")
        .orderBy("o.owner_name")

Your initial attempt was close, but you were missing the avg aggregate function while selecting directly from the ratings field. By properly aggregating the ratings and creating an alias 'avg', you can then select that alias along with the owner's name for the desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

How to properly store response text in JavaScript variable?

Utilizing Ajax to execute a PHP script on my website, I aim to assign the response from the PHP script to a JS variable. The objective is for this script to set the variable "stopAt" to 42. This is where I encountered an issue: Below is the code snippet ...

Limit access to the server in Node.js by allowing loading only if the request is coming from another page and form POST variables are present

After searching for documentation without success, I have a question: Is there a way to prevent users from directly accessing my node.js server at website.com:3000? Currently, when a user visits my node.js website, it crashes the whole server and takes i ...

How can I use jQuery to switch classes or activate a click event on the most recently clicked element?

Within my <ul></ul>, there are 4 <li> elements. <ul class="wcarchive-terms-list"> <li class="wcarchive-term wcarchive-term-parent woof_term_224"> <label class="wcarchive-term-label"> <span cla ...

AngularJS ng-map defines the view position using rectangular coordinates

Is there a way to set the position of ng-map view using the ng-map directive not as the center value of [40.74, -74.18], but instead as a rectangle defined by the corner values of the map view (north, south, east, west)? Currently, I have this code: < ...

Struggling to populate dropdown with values from array of objects

My issue is related to displaying mock data in a dropdown using the SUIR dropdown component. mock.onGet("/slotIds").reply(200, { data: { slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }] } }); I'm fetching and updating state with the data: const ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

When I scroll and update my webpage, the navigation header tends to lose its distinct features. This issue can be resolved

When I scroll, my navigation header changes from being transparent to having a solid color, and this feature works perfectly. However, whenever I refresh the page while already halfway down, the properties of my navigation header are reset and it reverts ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows: arr1=[{room_no:1,bed_no:'1A'}, {room_no:1,bed_no:'1B'}, {room_no:2,bed_no:'2A'}, {room_no:3,bed_no:'3A'}, {room_no:3,bed_no:'3B ...

Warnings about NgZone timeouts are displayed in Chrome DevTools even though the timeouts are actually executing outside of the

Is it common to receive a warning in Chrome DevTools like this? [Violation] 'setTimeout' handler took 103ms zone.js:1894 even when all timeouts are executed outside of ngzone? I personally follow this approach: this.zone.runOutsideAngular(() = ...

Elevate to Babel 7: Unable to access the property 'bindings' of null

I recently made the switch to Babel 7 (upgrading from version 6) using the following commands: npm remove babel-cli npm install --save-dev @babel/cli @babel/core @babel/preset-env This is the content of my .babelrc file: { "presets": ["env"] } After th ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Nodemon causing server to fail to start or connect

I recently set up a new project using Express, Node, and Nodemon. I configured the basic files to ensure it starts properly, but when I run npm start in the terminal, it seems to initiate without any errors being displayed regarding the server's locat ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Validation of the Twilio mobile number failed - Unable to locate VerificationCheck on Express

The console is displaying an error that the requested resource /Services/serviceSSID/VerificationCheck was not found. Below is the code snippet causing this issue: otpLogin:async (req,res)=>{ console.log(req.body.otp); try { const isOT ...