我想在同一行中将SwipeTime和SwipeDescription拆分为一扇门的进入和退出。
当前这是表格的样子:
+5
userid || SwipeDescription || EmployeeName || SwipeTime
178 || Output On By Door || Alexandra Perez || 2019-08-07 08:00:56.453
178 || Output Off By Door|| Alexandra Perez || 2019-08-07 08:01:02.300
我希望数据看起来像这样:
SELECT
u.userid
--,u.name
,et.name AS SwipeDescription
,CASE
WHEN scs.FullName is NULL THEN u.name
WHEN scs.FullName is NOT NULL THEN 'C - ' + scs.FullName
END AS EmployeeName
,e.LoggedTime AS SwipeTime
,d.name AS Door
FROM [Users] AS u
LEFT JOIN [Events] AS e ON e.RecordIndex1=u.UserID
LEFT JOIN [EventTypes] AS et on e.EventTypeID = et.EventTypeID
join [Doors] AS d ON e.RecordIndex2 = d.DoorID
LEFT join SecurityContractorSignIn as scs on scs.Badge = u.lastname and SignInTime > CONVERT(DATE, GETDATE())
WHERE LoggedTime > CONVERT(DATE, GETDATE()) and d.doorid in (32, 50, 42, 51, 33)
ORDER BY u.name,e.LoggedTime ASC
答案 0 :(得分:0)
SELECT * FROM dbo.Users WITH (NOLOCK)
SELECT Main.userid,
Main.SwipeDescription,
Main.EmployeeName,
Main.SwipeTime
FROM
(
SELECT U.userid,
U.SwipeDescription,
U.EmployeeName,
CONVERT(VARCHAR(40),U.SwipeTime,121)+' || '
+(SELECT SUB.SwipeDescription+' || '+CONVERT(VARCHAR(40),SUB.SwipeTime,121)
FROM
(SELECT ROW_NUMBER() OVER(PARTITION BY U.userid ORDER BY T.userID,U.SwipeTime) AS RowNum,
T.SwipeDescription,
T.UserID,
T.SwipeTime
FROM Users T
WHERE T.UserID=U.UserID)AS Sub
WHERE Sub.RowNum>1 ) AS SwipeTime,
ROW_NUMBER() OVER(PARTITION BY U.userid ORDER BY U.SwipeTime DESC) AS RowNum
FROM dbo.Users U WITH (NOLOCK)
) AS Main
WHERE Main.RowNum=1