如何在SQL Server中的两列中拆分单列数据

时间:2014-05-09 14:47:49

标签: sql-server sql-server-2008

userid   checkTime              type
------------------------------------
10       2014-01-11 10:41:37    IN
10       2014-01-11 18:12:37    OUT

如何在SQL Server中将此数据更改为此类

userid   time in               timeOut
--------------------------------------------------
10       2014-01-11 10:41:37   2014-01-11 18:12:37

2 个答案:

答案 0 :(得分:1)

SELECT x.userid,
       x.[time in],
       x.[time out]
FROM
    (SELECT userid, 
            checkTime AS 'time in',
            NULL AS 'time out'
     FROM table
     WHERE type = 'IN'
     UNION ALL
     SELECT userid, 
            NULL AS 'time in',
            checkTime AS 'time out'
     FROM table
     WHERE type = 'OUT') AS x

答案 1 :(得分:0)

你可以使用pivot:

SELECT userid, [IN], [OUT]
FROM yourtable
PIVOT
(
MIN(checkTime)
FOR TYPE IN([IN],[OUT])
) AS P