SQL Server中的部分数据透视

时间:2017-04-29 07:23:46

标签: sql sql-server pivot pivot-table

我有一个格式如下的SQL表

    Date                        Process1                     Process2               ...
2017-04-10 00:00:00.0000000 2017-04-11 02:49:10.0000000 2017-04-11 04:08:10.0000000 ...
2017-04-11 00:00:00.0000000 2017-04-12 02:55:09.0000000 NULL                        ...

我想以下列格式转动表格

            Date                ProcessName     ProcessTime
2017-04-10 00:00:00.0000000     Process1        2017-04-11 02:49:10.0000000
2017-04-10 00:00:00.0000000     Process2        2017-04-11 04:08:10.0000000
2017-04-11 00:00:00.0000000     Process1        2017-04-12 02:55:09.0000000
2017-04-11 00:00:00.0000000     Process2        NULL

有人可以帮我解决一下我该怎么办?

提前致谢!

2 个答案:

答案 0 :(得分:2)

调用UNPIVOT而不是PIVOT

select  *
from    yourtable
        unpivot
        (
             ProcessTime for ProcessName in (Process1, Process2)
        ) u

另请参阅Using PIVOT and UNPIVOT

或者,您可以使用UNION ALL

执行此操作
select  Date, ProcesTime = Process1, ProcessName = 'Process1' from yourtable union all
select  Date, ProcesTime = Process2, ProcessName = 'Process2' from yourtable 

答案 1 :(得分:0)

使用UNPIVOT方法:

 CREATE TABLE #table1 ( Date DATETIME, Process1 DATETIME , Process2 
            DATETIME) 

 INSERT INTO #table1 ( Date , Process1 , Process2 )
 SELECT '2017-04-10 00:00:00','2017-04-11 02:49:10','2017-04-11 04:08:10' 
 UNION ALL
 SELECT '2017-04-11 00:00:00','2017-04-12 02:55:09',NULL

 SELECT Date,ProcessName,ProcessTime
 FROM 
 (
   SELECT  Date , Process1 , Process2  
   FROM #table1
 ) A
 UNPIVOT 
 (
   ProcessTime  FOR ProcessName IN (Process1 ,  Process2)
 ) UnPvt