I have this table in access
Userinfo
userid | Name | dept id |
---|---|---|
1 | JJ | 002 |
2 | KK | 001 |
Dept
deptid | Dept Name |
---|---|
001 | Testing |
002 | Sorting |
003 | Designing |
Checkinout
userid | Name | Checktime | Checktype |
---|---|---|---|
1 | JJ | 2/5/2022 7:45:10 AM | 1 |
1 | JJ | 2/5/2022 18:00:10 PM | 0 |
1 | JJ | 2/6/2022 6:30:00 AM | 1 |
1 | JJ | 2/6/2022 18:10:30 PM | 0 |
2 | KK | 2/6/2022 6:10:30 AM | 1 |
2 | KK | 2/6/2022 18:20:30 PM | 0 |
But i want to create a Inner join that will show this table
userid | Name | Deptname | In | Out |
---|---|---|---|---|
1 | JJ | Sorting | 2/5/2022 7:45:10 AM | 2/5/2022 18:00:10 PM |
1 | JJ | Sorting | 2/6/2022 6:30:00 AM | 2/6/2022 18:10:30 PM |
1 | KK | Testing | 2/6/2022 6:10:30 AM | 2/6/2022 18:20:30 PM |
This is the SQL that i used but i dont know how to put 0 as Out and 1 as In
SELECT Userinfo.userid as ID,UserInfo.Name as Name,Dept.DeptName as Dept , Checkinout.Checktime
from ( Userinfo
inner join Checkinout on Userinfo.userid = Checkinout.userid )
inner join Dept on Userinfo.DeptId =Dept.DeptId ;
CodePudding user response:
Starting from the non-normalized Checkinout you can get everything but Out directly. Then add a calculated field to the query to look up the appropriate Out Checktime for each In Checktime:
Out: (SELECT TOP 1 q.Checktime FROM [Checkinout] as q WHERE (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC)
SQL:SELECT Userinfo.userid, Userinfo.Username, Dept.[Dept Name], Checkinout.Checktime AS [In], (SELECT TOP 1 q.Checktime FROM [Checkinout] as q WHERE (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC) AS Out
FROM (Dept INNER JOIN Userinfo ON Dept.deptid = Userinfo.[dept id]) INNER JOIN Checkinout ON Userinfo.userid = Checkinout.userid
WHERE (((Checkinout.Checktype)=1))
'I used a nested query for the calculated field and calculated Out with the business rules that each user check-in must have a corresponding and later check-out by the same user without any check-in/check-outs between.