我有一个表审核登录,我想为每个用户提取最新的登录信息,以下sql完成。
如何将sql查询格式化为linq to sql查询?
SELECT * FROM AuditTable adt1
inner join UserTable usr
on adt1.[UserName] = usr.[User_Id]
WHERE [TimeStamp] = ( SELECT MAX([TimeStamp])
FROM AuditTable adt2
WHERE adt1.UserName = adt2.UserName)
在sql中编写查询的另一种方法是;
SELECT adt1.[UserName], usr.First_Name, max([TimeStamp]) as [TimeStamp]
FROM AuditTable adt1
INNER JOIN UserTable usr
on adt1.[UserName] = usr.[User_Id]
GROUP BY adt1.[UserName] ,usr.First_Name
答案 0 :(得分:2)
查询#2:
来自ad.1 in dc.AuditTable
在adt1.UserName == usr.UserID上加入dc.UserTable中的usr
group adt1 by adt1.username int ag
选择新{UserName = ag.Key,TSMax = ag.Max(ts => adt1.TimeStamp)}
为什么要加入用户表?过滤
答案 1 :(得分:0)
我开始工作......答案是使用let关键字。
另外,我强烈建议您在尝试解决这些问题时使用LinqPad。
from adt in AuditTable
join usr in UserTable
on adt.UserName equals usr.User_Id
group adt by
new { adt.UserName, adt.Roles, usr.First_Name, usr.Last_Name }
into g
let LastAccessed = g.Max(a => a.TimeStamp)
select new
{ UserName = g.Key.UserName,
Roles = g.Key.Roles,
FirstName = g.Key.First_Name,
LastName = g.Key.Last_Name,
TimeStamp = LastAccessed
}