Votes Requests for Top Positions Based on Percentage
I have a table of votes that looks like this:
id, type, scope, region, UserId, ItemId, updatedAt, createdAt
I am trying to sum the top positions by percentages based on votes / total votes.
The last part is the proposal WHERE
for votes createdAt
between two timestamps.
I feel like this is a very normal thing for querying statistics. But I'm not sure how to do this.
The closest I got was:
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"
It's a long way from what it takes. So I would like to help here. It was very difficult to find good sql resources on things like this.
+3
source to share
2 answers
You can do it with conditional aggregation:
select itemid,
sum(case when type = 'up' then 1 else 0 end) up,
sum(case when type = 'down' then 1 else 0 end) down,
sum(1) total,
100.0*sum(case when type = 'up' then 1 else 0 end)/sum(1) upperc,
100.0*sum(case when type = 'down' then 1 else 0 end)/sum(1) downperc
from votes
group by itemid
+2
source to share