1
votes

I have the following sql select statement that I am trying to convert to 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]

The results should look like the following:

SQL Results

I've got the following so far:

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
              })

I'm stuck on how to write the inner join with the additional select statement and the 'CASE' statements.

Any help would be appreciated.

1

1 Answers

0
votes

you can use Lambda expressions group by and for conditional select use inline condition like below:

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,
            });