I’m trying to create a query to get the voting results.
There is a table which records every vote someone makes. It is possible for people to vote multiple times, but only the last vote should be taken into account.
I’m at the point that it works, except the ‘only the last vote of a user should be taken into account’ part.
This is my table:
Table Vote:
id bigint PK
TimeStamp datetime
QuestionId int
UserId int
and the Linq query:
var total = (float)(_db.Votes).Count(vote => vote.Timestamp>=startWeekDay && vote.Timestamp<endWeekDay);
var results = (from vote in _db.Votes
where vote.Timestamp >= startWeekDay && vote.Timestamp < endWeekDay
group vote by new { vote.QuestionId} into g
orderby g.Count() descending
select new VoteResults()
{
QuestionID = g.Key.QuestionId,
Percentage = (g.Count() / total * 100.0f),
}).ToList();
My question: how do I change this query so that only the last cast vote per user is taken into account?
EDIT:
Given this input:
{
UserId = 1,
QuestionId = 2,
TimeStamp = Yesterday
},
{
UserId = 1,
QuestionId = 1,
TimeStamp = Today
},
{
UserId = 2,
QuestionId = 2,
TimeStamp = Yesterday
},
{
UserId = 3,
QuestionId = 1,
TimeStamp = Yesterday
}
The output should look like this:
{
QuestionID = 2,
Percentage = 33.3333
},
{
QuestionID = 1,
Percentage = 66.66666
}
Bellow I show you a test case I ran in a Console App… It should solve your problem. I tested with the data you passed in your example: