将数据连接到单个列中

Joining Data into a Single Column

我有这个table在访问

用户信息

userid Name dept id
1 JJ 002
2 KK 001

部门

deptid Dept Name
001 Testing
002 Sorting
003 Designing

签到

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

但我想创建一个将显示此内容的内部联接 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

这是我用过的 SQL,但我不知道如何将 0 设为 Out,将 1 设为 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 ;

从 non-normalized Checkinout 开始,您可以获得除直接 Out 之外的所有内容。然后在查询中添加一个计算字段,为每个 In Checktime 查找合适的 Out 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.