Well, I have this 2 tables:
CREATE TABLE `bookRating` (
`userId` INT NOT NULL,
`isbn` VARCHAR(13) NOT NULL,
`rate` INT NOT NULL,
`date` DATE NOT NULL,
CONSTRAINT `fk_bookRating_user` FOREIGN KEY (`userId`) REFERENCES `user`(`userId`),
CONSTRAINT `fk_bookRating_book` FOREIGN KEY (`isbn`) REFERENCES `book`(`isbn`)
);
CREATE TABLE `user` (
`userId` INT UNIQUE NOT NULL AUTO_INCREMENT,
`country` VARCHAR(3) NOT NULL,
`age` INT NOT NULL,
PRIMARY KEY (`userId`),
CONSTRAINT `fk_user_country` FOREIGN KEY (`country`) REFERENCES `country`(`code`)
);
I wanted to split the table user into 3 categories. users.age <= 30 , 30 < users.age <= 50 , users.age > 50 and then find the average rating for each category
I figured I could do something like this:
WITH people_age_less_than_30 AS (
SELECT COUNT(*) count_less_than_30, AVG(`bookRating`.`rate`) as avg_Book_rating_less_30 FROM `user`
INNER JOIN `bookRating` on `user`.`userId` = `bookRating`.`userId`
WHERE `user`.`age` <= 30
),
people_age_between_30_50 as (
SELECT COUNT(*) count_between_30_50, AVG(`bookRating`.`rate`) as avg_Book_between_30_50 FROM `user`
INNER JOIN `bookRating` on `user`.`userId` = `bookRating`.`userId`
WHERE `user`.`age` BETWEEN 30 AND 50
),
people_age_above_50 as (
SELECT COUNT(*) count_more_than_50, AVG(`bookRating`.`rate`) as avg_Book_rating_above_50 FROM `user`
INNER JOIN `bookRating` on `user`.`userId` = `bookRating`.`userId`
WHERE `user`.`age` > 50
)
select count_less_than_30, avg_Book_rating_less_30, count_between_30_50, avg_Book_between_30_50, count_more_than_50, avg_Book_rating_above_50
from people_age_less_than_30 join people_age_between_30_50 join people_age_above_50;
This way I know it works! But
I don't think that this is the best way to do what I want to, this is why I am asking, is there an other way to do the same thing? A "better" way?