我正在尝试创建一个查询来获取投票结果。
有一张表格记录了某人所做的每一次投票。人们可以多次投票,但只应考虑最后一次投票。
除了“只应考虑用户的最后一票”部分之外,我正处于它可以工作的地步。
这是我的桌子:
表投票:
id bigint PK
TimeStamp datetime
QuestionId int
UserId int
和 Linq 查询:
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();
我的问题:如何更改此查询,以便仅考虑每个用户的最后一次投票?
编辑:鉴于此输入:
{
UserId = 1,
QuestionId = 2,
TimeStamp = Yesterday
},
{
UserId = 1,
QuestionId = 1,
TimeStamp = Today
},
{
UserId = 2,
QuestionId = 2,
TimeStamp = Yesterday
},
{
UserId = 3,
QuestionId = 1,
TimeStamp = Yesterday
}
输出应如下所示:
{
QuestionID = 2,
Percentage = 33.3333
},
{
QuestionID = 1,
Percentage = 66.66666
}