2009-08-07 64 views
0

我有一個表審計登錄,我想提取每個用戶的最新登錄,下面的sql完成。使用group by子句和/或聚合函數將sql查詢轉換爲linq to sql?

我如何將sql查詢格式化爲一個linq到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

我得到它的工作...答案是使用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 
    } 
2

查詢#2:
從adt1在dc.AuditTable
在dc.UserTable上adt1.UserName == usr.UserID
組adt1加入USR由adt1.username INT公司
新選擇{UserName = ag.Key,TSMax = ag.Max(ts => adt1.TimeStamp)}

爲什麼加入用戶表?過濾?

+0

謝謝,到底有沒有完整的答案在下面.. :-) – 2009-08-07 10:51:38

相關問題