我需要一个读取此表的SQL语句:
这会返回包含一天所有登录信息的动态列,按EmployeeId
进行分组。
EmployeeId, Login1, Logoff1, Login2, Logoff2, Login3, Logoff3
答案 0 :(得分:3)
DECLARE @TABLE TABLE (EmployeeID INT, LoginTime DATETIME , LogoffTime DATETIME)
INSERT INTO @TABLE VALUES
( 49 , '2015-04-07 00:16:22.307' , '2015-04-07 00:16:30.307'),
( 49 , '2015-04-07 00:17:22.307' , '2015-04-07 00:17:39.307'),
( 8 , '2015-04-06 00:16:22.307' , '2015-04-06 00:16:30.307'),
( 8 , '2015-04-07 00:16:22.307' , '2015-04-07 00:16:28.307'),
( 55 , '2015-04-05 00:16:22.307' , '2015-04-07 00:16:22.307')
SELECT *
FROM (
SELECT EmployeeID
,Dates
, Login_Logoff + '_'
+ CAST(ROW_NUMBER() OVER
(PARTITION BY EmployeeID,Login_Logoff
ORDER BY Dates ASC) AS NVARCHAR(10)) AS [Login_Logoff]
FROM @TABLE
UNPIVOT (Dates FOR Login_Logoff IN (LoginTime,LogoffTime))up
) T
PIVOT (MAX(Dates)
FOR Login_Logoff
IN (LoginTime_1,LogoffTime_1,LoginTime_2,LogoffTime_2))p
╔════════════╦═════════════════════════╦═════════════════════════╦═════════════════════════╦═════════════════════════╗
║ EmployeeID ║ LoginTime_1 ║ LogoffTime_1 ║ LoginTime_2 ║ LogoffTime_2 ║
╠════════════╬═════════════════════════╬═════════════════════════╬═════════════════════════╬═════════════════════════╣
║ 8 ║ 2015-04-06 00:16:22.307 ║ 2015-04-06 00:16:30.307 ║ 2015-04-07 00:16:22.307 ║ 2015-04-07 00:16:28.307 ║
║ 49 ║ 2015-04-07 00:16:22.307 ║ 2015-04-07 00:16:30.307 ║ 2015-04-07 00:17:22.307 ║ 2015-04-07 00:17:39.307 ║
║ 55 ║ 2015-04-05 00:16:22.307 ║ 2015-04-07 00:16:22.307 ║ NULL ║ NULL ║
╚════════════╩═════════════════════════╩═════════════════════════╩═════════════════════════╩═════════════════════════╝