在SQL Server中转置列并删除不需要的列?

时间:2016-09-08 09:55:13

标签: sql-server transpose

我有一张这样的表:

Dimension Code      Dimension Value Code    Entry No_
BUSINESSSEGMENTS       153                     1
TERMINAL               41150                   1

我想转置它,因为我正在使用此查询:

select  *
from realTable
unpivot (value for DimValCode in ([Dimension Value Code])) up
pivot (max(value) for [Dimension Code] in (BUSINESSSEGMENTS,TERMINAL)) p

它工作正常并提供如下输出:

Entry No_     DimValCode                   BUSINESSSEGMENTS     TERMINAL
   1          Dimension Value Code              153              41150

但我需要这个:(不需要DimValCode列)

Entry No_       BUSINESSSEGMENTS    TERMINAL
  1                  153             41150

我需要在此查询中修改哪些内容?

感谢。

1 个答案:

答案 0 :(得分:0)

试试这个,

SELECT [Entry No_]
    ,[BUSINESSSEGMENTS]
    ,[TERMINAL]
FROM (
    SELECT *
    FROM realTable
    unpivot(value FOR DimValCode IN ([Dimension Value Code])) up
    pivot(max(value) FOR [Dimension Code] IN (
                BUSINESSSEGMENTS
                ,TERMINAL
                )) p
    ) T