Skip to content

Instantly share code, notes, and snippets.

@ArtOfCode-
Created May 16, 2018 13:59
Show Gist options
  • Save ArtOfCode-/acb816ce044cb2ea623c822fb3d5a6c1 to your computer and use it in GitHub Desktop.
Save ArtOfCode-/acb816ce044cb2ea623c822fb3d5a6c1 to your computer and use it in GitHub Desktop.
SELECT
TRUNCATE(p1.reason_weight, -1) AS weight,
COUNT(DISTINCT p2.id) / @total AS probability
FROM (
SELECT
posts.id,
SUM(reasons.weight) AS reason_weight
FROM posts
INNER JOIN posts_reasons ON posts.id = posts_reasons.post_id
INNER JOIN reasons ON posts_reasons.reason_id = reasons.id
GROUP BY posts.id
) AS p1
INNER JOIN (
SELECT
posts.id,
SUM(reasons.weight) AS reason_weight
FROM posts
INNER JOIN posts_reasons ON posts.id = posts_reasons.post_id
INNER JOIN reasons ON posts_reasons.reason_id = reasons.id
GROUP BY posts.id
) AS p2 ON TRUNCATE(p2.reason_weight, -1) <= TRUNCATE(p1.reason_weight, -1)
GROUP BY TRUNCATE(p1.reason_weight, -1)
ORDER BY TRUNCATE(p1.reason_weight, -1) ASC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment