简体   繁体   中英

How do I this query correct

I have 3 tables like this. For my homework I have to make a query which is Select a Dvd name, dvd category and average of rates for criticized by at least two customer

     CREATE TABLE dvd(
    `dvdId` INT NOT NULL,
    `Name` VARCHAR(45) NULL,
    `Category` VARCHAR(45) NULL,
   `Price` INT NOT NULL,
    PRIMARY KEY (`Id`));  

     CREATE TABLE Subtitles(
    `dvdId` INT NOT NULL,
    `Language` VARCHAR(45) NULL);
     
   CREATE TABLE critic(
    `dvdId` INT NOT NULL,
   `customerName` VARCHAR(45) NULL,
   `rate` INT NOT NULL,
   `comment` VARCHAR(45) NULL);

I'm trying to do this but this query doesn't work as I wish. Can anyone help me?

SELECT name,catergory, avg(rate) as rate FROM Dvd INNER JOIN Critic ON 
Dvd.dvdId=Critic.DvdId
GROUP BY customerName
HAVING COUNT(*) >2;

Try this below script-

The basic of GROUP BY is, that you have to GROUP BY with all non aggregated columns you selected in the SELECT part of your query. In your query, you have selected name and catergory column as non aggregated column, but did not added them in the GROUP BY properly.

SELECT name,Category, -- you have wrong column name "Category" in your query
avg(rate) as rate 
FROM Dvd 
INNER JOIN Critic 
ON Dvd.dvdId=Critic.DvdId
GROUP BY name,Category
-- Add all non aggregated columns in the GROUP BY from the SELECT part
HAVING COUNT(*) >2;

Note: You can also add column "customerName" in both SELECTION and GROUP BY part if the value is required. But just keep in mind, adding a new column in GROUP BY means creating new dimensions/groups in the output. So you have be careful of adding columns in GROUP BY.

You should add all non-aggregated fields in group by . Here is really good read about why the selected column have to be in the group by clause.

Always try to alias your tables and try the following.

SELECT 
  name,
  catergory, 
  avg(rate) as rate 
FROM Dvd d
JOIN Critic c
ON d.dvdId = c.DvdId
GROUP BY 
  name,
  catergory
HAVING COUNT(*) > 2

Change your sql as below:-

SELECT name,catergory, customerName, avg(rate) as rate 
FROM Critic left join Dvd  ON Dvd.dvdId=Critic.DvdId
GROUP BY customerName
HAVING COUNT(customerName) >1;

Let me know if it solves your issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM