Last active
December 20, 2015 13:39
-
-
Save rmcauley/6140343 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH | |
faves AS ( | |
SELECT album_id, album_fave, user_id, 0 AS album_rating_user | |
FROM (DELETE FROM r4_album_ratings WHERE album_id = 390 RETURNING *) | |
), | |
ratings AS ( | |
SELECT album_id, FALSE AS album_fave, user_id, ROUND(CAST(AVG(song_rating_user) AS NUMERIC), 1) AS album_rating_user | |
FROM r4_song_album LEFT JOIN r4_song_ratings USING (song_id) | |
WHERE r4_song_album.album_id = 390 | |
GROUP BY album_id, user_id | |
) | |
INSERT INTO r4_album_ratings (album_id, user_id, album_fave, album_rating_user) | |
SELECT album_id, user_id, BOOL_OR(album_fave) AS album_fave, NULLIF(MAX(album_rating_user), 0) AS album_rating_user | |
FROM (SELECT * FROM faves UNION ALL SELECT * FROM ratings) AS fused | |
GROUP BY album_id, user_id | |
HAVING BOOL_OR(album_fave) = TRUE OR MAX(album_rating_user) IS NOT NULL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment