如何从sql查询中编写内联linq查询

时间:2014-05-21 12:01:19

标签: asp.net linq

以下查询是用sql编写的,用于根据上次活动日期选择销售人员的近期活动

select UDV.User_dailyActivityId,UDV.userId,UDV.[DATE] ActivityDate,UDV.Activity,UDV.Subject 
      From [SalesTrack].[dbo].[UserDailyActivity]  UDV,
      (
        Select  userId,Max([DATE]) ActivityDate from [SalesTrack].[dbo].[UserDailyActivity]
        Group by userId
       ) GPUDV

      where udv.userId = GPUDV.userId and UDV.[DATE] = gpudv.ActivityDate
      order by udv.userId,UDV.[DATE]

我必须将上述查询更改为linq,我是linq中的新手

我成功编写了内联查询部分

var lastgroup=(from ua in db.UserDailyActivities group ua by ua.userId into GPua select new{GPua,ActivityDate=GPua.Max(ua=>ua.date)});  

请帮我完成整个查询

1 个答案:

答案 0 :(得分:0)

也许是这样的:

var result=
    (
        from UDV in db.UserDailyActivity
        from GPUDV in
        (
            from inner in db.UserDailyActivity
            group inner by inner.userId into g
            select new
            {
                userId=g.Key,
                ActivityDate=g.Max (x =>x.DATE)
            }
        ).Where (w =>w.userId==UDV.userId && w.ActivityDate==UDV.DATE)
        select new
        {
            UDV.User_dailyActivityId,
            UDV.userId,
            ActivityDate = UDV.[DATE],
            UDV.Activity,
            UDV.Subject
        }
    ).ToList();

其中db是linq数据上下文