使用linq对组执行右外连接

时间:2015-04-08 21:57:26

标签: c# sql-server linq

我无法设计linq查询,以查找特定月份的活跃用户数。

以下是我的课程:

public class Reg_User
{
    int userID { get; set; }          
    DateTime dateStart { get; set; }
}


public class Reg_User_Log
{
    int userID { get; set; }
    DateTime dateModified { get; set; }
    bool deactivationStatus { get; set; }
}

仅当帐户被停用或重新激活时才会创建Reg_User_Log记录,因此新帐户将没有关联的日志。

用户将指定我们将调用specifiedDate的月份和年份,我需要查找在指定时间之前没有日志文件的dateStart时间的用户,以及最近的那些用户指定月份和年份之前的日志文件的deactivationStatus值为false。

我这样做的sql查询如下:

SELECT 
   usr.id
  ,max([dateModified]) as 'last modified date'
  ,(select deactivationStatus from tbl_reg_user_log ilg where userid = usr.id and dateModified = max(lg.datemodified))
  FROM [IO].[dbo].[tbl_reg_user_log] lg
right outer join tbl_reg_user usr on lg.userID = usr.id
  where usr.clientid = specifiedID and (lg.dateModified <= specifiedDate or lg.dateModified is null) and date_Start <= specifiedDate
  group by usr.id

此查询未考虑停用状态为true的日志 - 我还没有想到该部分。

1 个答案:

答案 0 :(得分:0)

我想我最后通过将其分解为两个独立的linq查询来解决这个问题。

temp是下个月第一天的DateTime

//Obtains all users who have never been deactivated and were created prior to the month in question
newRecord.TotalUsers = (from usr in db.tbl_Reg_User
                        join lg in db.tbl_reg_user_log on new { UserID = usr.ID } equals new { UserID = lg.userID } into lg_join
                        from lg in lg_join.DefaultIfEmpty()
                        where (usr.date_Start < temp) && usr.clientID == j.clientID && usr.clientID != 1
                        where lg.dateModified == null
                        select usr.ID).Count();

//Obtains users who were deactivated at some point but were reactivated prior or during the month in question
newRecord.TotalUsers += (from usr in db.tbl_Reg_User
                            join lg in db.tbl_reg_user_log on new { UserID = usr.ID } equals new { UserID = lg.userID } into lg_join
                            from lg in lg_join.DefaultIfEmpty()
                            where (usr.date_Start < temp) && usr.clientID == j.clientID && usr.clientID != 1
                            where lg.dateModified != null && lg.dateModified < temp
                            orderby lg.dateModified descending
                            group lg by lg.userID into g
                            select g).Select(x => x.Where(y => y.deactivationStatus != true)).Count();