我的用户活动日志如下所示:
ID、用户名、日期
我需要计算每天的条目总数,以及过去 10 天当天最活跃的用户。
//pseudo code
from entry in data.UserLogs
group by entry.Date == each day
select username of most active user, count(Id)
我是 LINQ 和 SQL 的新手,有人可以帮我完成这个查询吗?
我想这就是你所追求的。只需将其放入 LINQPad 即可查看它的运行情况
void Main()
{
var logs = new List<UserLog>
{
new UserLog { Id= 1, Date = new DateTime(2012,1,1), Username = "cburgdorf"},
new UserLog { Id= 2, Date = new DateTime(2012,1,1), Username = "cburgdorf"},
new UserLog { Id= 3, Date = new DateTime(2012,1,1), Username = "cburgdorf"},
new UserLog { Id= 4, Date = new DateTime(2012,1,1), Username = "Mister Foo"},
new UserLog { Id= 5, Date = new DateTime(2012,1,1), Username = "Mister Foo"},
new UserLog { Id= 6, Date = new DateTime(2012,1,2), Username = "Mister Bar"},
new UserLog { Id= 7, Date = new DateTime(2012,1,2), Username = "Mister Bar"},
new UserLog { Id= 8, Date = new DateTime(2012,1,2), Username = "cburgdorf"},
new UserLog { Id= 9, Date = new DateTime(2012,1,2), Username = "Mister Foo"},
new UserLog { Id= 10, Date = new DateTime(2012,1,2), Username = "Mister Foo"},
new UserLog { Id= 11, Date = new DateTime(2012,1,2), Username = "Mister Foo"},
new UserLog { Id= 12, Date = new DateTime(2012,1,2), Username = "Mister Bar"}
};
logs
.OrderByDescending (l => l.Date)
.GroupBy (log => log.Date)
.Select (log => log
.GroupBy (l => l.Username)
.Select (l => new
{
Count = l.Count (),
Value = l.FirstOrDefault (),
})
.OrderBy (l => l.Count).Last ())
.Select (log => new
{
Date = log.Value.Date,
Count = log.Count,
Username = log.Value.Username
})
.Take(10)
.Dump();
//In LINQPad use Dump() to see the results:
/*
logs
.OrderByDescending (l => l.Date)
.GroupBy (log => log.Date)
.Select (log => log
.GroupBy (l => l.Username)
.Select (l => new
{
Count = l.Count (),
Value = l.FirstOrDefault (),
})
.OrderBy (l => l.Count).Last ())
.Select (log => new
{
Date = log.Value.Date,
Count = log.Count,
Username = log.Value.Username
})
.Take(10)
.Dump();
*/
}
class UserLog
{
public int Id {get;set;}
public DateTime Date {get;set;}
public string Username {get;set;}
}
The result is:
02.01.2012 00:00:00 | 3 | Mister Foo
01.01.2012 00:00:00 | 3 | cburgdorf
这应该行得通。这将选择最近 10 天内排名最高的用户。
var query =
(from userLog in data.UserLogs
group userLog.UserName by userLog.Date.Date into usersPerDate
orderby usersPerDate.Key descending
let topUsers =
from user in usersPerDate
group 1 by user into g
let count = g.Count()
orderby count descending
select new
{
UserName = g.Key,
Count = count,
}
select topUsers.First()).Take(10);