SQL Server创建动态列Login1,Login2,Login3

时间:2015-04-06 22:35:20

标签: sql sql-server tsql

我需要一个读取此表的SQL语句:

Table1

这会返回包含一天所有登录信息的动态列,按EmployeeId进行分组。

EmployeeId, Login1, Logoff1, Login2, Logoff2, Login3, Logoff3

1 个答案:

答案 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                    ║
╚════════════╩═════════════════════════╩═════════════════════════╩═════════════════════════╩═════════════════════════╝