2015-06-28 59 views
1

我有我需要轉換爲LINQ這個SQL查詢:什麼是LINQ中SQL的最大功能等價物?

SELECT * 
FROM USER U 
INNER JOIN (
    SELECT USERID , MAX(SALESDATE) AS MAXDATE 
    FROM SALES 
    GROUP BY USERID) S ON U.ID = S.USERID 

到目前爲止,這是我想出LINQ:

var Users = (from d in db.Users 
      join s in db.Sales on d.Id equals s.UserId 
      select new Models.User 
      { 
       Id = d.Id, 
       UserName = d.UserName, 
       FirstName = d.FirstName, 
       LastName = d.LastName, 
       EmailAddress = d.EmailAddress, 
       PhoneNumber = d.PhoneNumber, 
       LastPurchase = s.SalesDate 
      }).Max(x => x.SalesDate); 

不過,我敢肯定結果是不一樣的。任何人都可以建議將其轉換爲LINQ的正確方法嗎?我還是學習LINQ的新手。我非常感謝幫助。

回答

0

試試這個

var Users = (from d in db.Users 
      from s in db.Sales.where(x=>x.Userid==d.id).groupby(x=>x.Userid) 
      select new Models.User 
      { 
       Id = d.Id, 
       UserName = d.UserName, 
       FirstName = d.FirstName, 
       LastName = d.LastName, 
       EmailAddress = d.EmailAddress, 
       PhoneNumber = d.PhoneNumber, 
       LastPurchase = s.Max(x=>x.SalesDate) 
      }).ToList(); 
0

您當前的LINQ查詢,首先加入對整個表,然後選擇違背了其在銷售榜第一選擇,然後你的SQL的一箇中加入了對這一結果(別名S你的例子)。

var query = from u in db.Users 
      join s in (from sale in db.Sales 
         group sale by sale.Id into grp 
         select new { 
          Id = grp.Key, 
          LastPurchase = grp.Max(item => item.SalesDate) 
         }) 
      on u.Id equals s.Id 
      select /* what you need to retrieve */; 
0

你可以這樣說:

 var query1 = from sale in db.Sales 
        group sale by sale.UserId into g 
        let maxDate = g.Max(s => s.SalesDate) 
        select new { UserId = g.Key, maxDate }; 

     var query2 = from user in db.Users 
        from q1 in query1.Where(q => q.UserId == user.Id) 
        select new { user.Id, user.UserName, user.Firstname, user.lastname, ... , q1.maxDate }; 

     var result = query2.ToList(); 
相關問題