linq内部联接子查询和条件选择

时间:2018-06-26 12:42:58

标签: sql entity-framework linq

我有以下SQL选择语句,我正在尝试将其转换为Linq:

SELECT a.lastname,a.firstname,a.program,a.[start],a.[end],
CASE WHEN a.[end] IS NULL AND a.[start] < c.lastStart THEN 1 ELSE 0 END as error,
CASE WHEN a.[end] IS NULL AND a.[start] = c.lastStart THEN 1 ELSE 0 END as loggedOn
FROM usagelog a 
INNER JOIN (SELECT b.username,max(b.[start]) AS lastStart FROM usagelog b GROUP BY b.username) c 
ON a.username = c.username
ORDER BY a.lastname, a.firstname,a.program,a.[start]

结果应如下所示:

SQL Results

到目前为止,我有以下内容:

var query = (from u in UsageLogs
             orderby u.lastname,u.firstname,u.program.u.start
             select new
             {
              lastname = u.lastname,
              firstname = u.firstname,
              program = u.program,
              start = u.start,
              end = u.end
              })

我对如何使用附加的select语句和'CASE'语句编写内部联接感到困惑。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用 Lambda表达式分组依据,并为条件选择使用内联条件,如下所示:

var query = (from u in UsageLogs
            join c in (UsageLogs.GroupBy(r => r.username).Select(r => new {username = r.Key, lastStart = r.Max(p => p.start)))
            on u.username equals c.username
            orderby u.lastname,u.firstname,u.program.u.start
            select new
            {
                lastname = u.lastname,
                firstname = u.firstname,
                program = u.program,
                start = u.start,
                end = u.end,
                error = (u.end == NULL && u.start < c.lastStart) ? 1 : 0,
                loggedOn = (u.end == NULL && u.start == c.lastStart) ? 1 : 0,
            });