sql-server - 将列拆分为每个输入/输出记录的单行
问题描述
我想将 SwipeTime 和 SwipeDescription 拆分在同一行用于门的入口和出口。
目前这是表格的样子:
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
我希望数据看起来像这样:
userid || SwipeDescriptionIn || EmployeeName || SwipeTimeIn
178 || Output On By Door || Alexandra Perez || 2019-08-07 08:00:56.453 || Output Off By Door|| 2019-08-07 08:01:02.300
解决方案
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
推荐阅读
- python - Matplotlib x 轴上的毫秒刻度
- android - 在 RecyclerView OnItemClickListener 上显示对话框
- flutter - 如何将下载的数据从 API 保存到 Flutter 中的 RAM?
- python - Django 自动建模多对多关系添加
- r - 如何计算期权的 Black-Scholes 看跌期权
- sorting - Kotin 按降序然后升序排序
- javascript - 仅 http cookie 中的 JWT 未定义
- c# - 附加 CSV 文件以回复 Microsoft Bot Framework for Teams
- google-cloud-platform - Google Speech to Text - LongRunningRecognize - PollUntilCompleted 返回购买操作仍未完成
- node.js - Apollo GraphQL Server 中的别名字段