Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Votes table top items based on a percentage

I have a table of Votes that looks like:

id, type, scope, region, UserId, ItemId, updatedAt, createdAt

I am trying to total the top items by percentage based on up votes / total votes.

Last piece is I want a WHERE clause for the votes for createdAt between two timestamps.

I feel like this is a very normal thing to query for getting statistics. But I am not sure how to go about this.

The closest I have gotten is:

SELECT "Votes"."ItemId", count("Votes"."ItemId") tots, count("Votes"."type" = 'up') AS yes, count("Votes"."type" = 'down') AS NO
FROM "Votes"
WHERE "Votes"."ItemId" IN (
    SELECT "Votes"."ItemId" FROM "Votes"
)
GROUP BY "Votes"."ItemId"

Which is a long ways from what is need. Hence why I would love some help here. Been having a really hard time finding good sql resources on this kind of stuff.

like image 989
corbanb Avatar asked Nov 19 '25 22:11

corbanb


1 Answers

You can use a CASE statement to use 1 for each up vote and -1 for down vote and get sum of them

SELECT ItemId, SUM(CASE [type] WHEN 'up' THEN 1 WHEN 'down' THEN -1 END)
FROM Votes
WHERE createdAt >= 'startTime'
AND createdAt <= 'endTime'
GROUP BY ItemId
like image 194
sqluser Avatar answered Nov 21 '25 12:11

sqluser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!