简体   繁体   中英

LINQ to SQL Group By Multiple Records in One Row

Sorry, I don't know how to describe in words, that's why the poor title.

I have a table as follows:

UserID Date Description
1 17/11/2020 09:00 Sign in
2 17/11/2020 09:00 Sign in
2 17/11/2020 12:00 Sign out
2 17/11/2020 13:00 Sign in
2 17/11/2020 16:00 Sign out
1 17/11/2020 17:00 Sign out

I am creating a report from this data. I need to show data as follows:

Date UserID SignIn SignOut
1 17/11/2020 09:00 17:00
2 17/11/2020 09:00 12:00
2 17/11/2020 13:00 16:00

I know I need to group on date and user but I need help getting the sign in/out times in the same row.

One method is conditional aggregation using row_number() :

select userid,
       max(case when description = 'Sign in' then date end) as signin,
       max(case when description = 'Sign out' then date end) as signout
from (select t.*, 
             row_number() over (partition by userid, description order by date) as seqnum
      from t
     ) t
group by userid, seqnum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM