I just started learning SQL a few days ago and I am working with some basic examples. In this example I want to find trainings that my friends and teammates like (based on how many of my friends liked the training, how many friends completed the training, and the average rating from my friends on the training). So far I used sub-queries to get me a weighted value for each type of weighted value per training. I want to sum the weighted values for each training giving each training a total and then order the training list by the total and select the top few from that.
Here is what I did.
SELECT training_id, (5* COUNT()) AS [value]FROM progress
WHERE user_id IN (SELECT friend_id AS user_ids FROM friendships WHERE user_id=6 UNION SELECT user_id FROM membership WHERE team_id IN (SELECT team_id FROM membership WHERE user_id = 6))
AND completed = 1
GROUP BY training_id
UNION ALL
SELECT training_id, (10 * AVG(rating))
FROM reviews
WHERE user_id IN (SELECT friend_id AS user_ids FROM friendships WHERE user_id=6 UNION SELECT user_id FROM membership WHERE team_id IN (SELECT team_id FROM membership WHERE user_id = 6))
GROUP BY training_id
UNION ALL
SELECT training_id, COUNT()
FROM likes
WHERE user_id IN (SELECT friend_id AS user_ids FROM friendships WHERE user_id=6 UNION SELECT user_id FROM membership WHERE team_id IN (SELECT team_id FROM membership WHERE user_id = 6))
GROUP BY training_id
The results look like:
training_id, value 1, 10 2 , 5 1 , 34.5 2 , 45 1 , 6 2 , 3
Please let me know if you know of a way to do this or if there is an alternative to this method that I should be looking at.
(the tables 'likes' 'reviews' and 'progress' all contain the field "training_id". What do you think about Joining the three tables to begin with?)
Aucun commentaire:
Enregistrer un commentaire