【问题标题】:Partial Pivot in SQL ServerSQL Server 中的部分透视
【发布时间】:2017-04-29 07:23:45
【问题描述】:

我有一个如下格式的 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

有人可以帮我看看我该怎么做吗?

提前致谢!

【问题讨论】:

    标签: sql sql-server pivot pivot-table


    【解决方案1】:

    这是调用 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 
    

    【讨论】:

      【解决方案2】:

      使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-26
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多