选择到PIVOT

时间:2019-01-15 10:48:54

标签: sql-server pivot-table

我在SQL中的表为:

DefultDim   Name,         DisplayValue
-------------------------------------
5637145329, B_MainSector,   4
5637145329, C_SecondSector, 401
5637145329, D_ThirdSection, 40100
5637145329, E_Vendor,       0032

我想使用select来查看:

DefultDim,  B_MainSector,   C_SecondSector, D_ThirdSection, E_Vendor
--------------------------------------------------------------------
5637145329   4             401              40100           0032

我使用以下代码:

select DEFAULTDIMENSION AS FULLDIM ,[0] AS B_MainSector ,[1] AS C_SecondSector ,[2] AS D_ThirdSection ,[3] AS E_Vendor
from
(select DEFAULTDIMENSION,NAME,RECID,DISPLAYVALUE from DEFAULTDIMENSIONVIEW )
P PIVOT  (max(DISPLAYVALUE) 
for DISPLAYVALUE in([0],[1],[2],[3])) as PVT 

但是结果似乎是:

DefultDim   B_MainSector    C_SecondSector  D_ThirdSection  E_Vendor
--------------------------------------------------------------------
5637145329, NULL,   NULL,   NULL,   NULL
5637145329, NULL,   NULL,   NULL,   NULL
5637145329, NULL,   NULL,   NULL,   NULL
5637145329, NULL,   NULL,   NULL,   NULL

请帮助。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下Pivot查询

create table #Temp (DefultDim Varchar(15), Name Varchar(15), DisplayValue Varchar(5))

Insert Into #Temp Values ('5637145329', 'B_MainSector', '4'),
('5637145329', 'C_SecondSector', '401'),
('5637145329', 'D_ThirdSection', '40100'),
('5637145329', 'E_Vendor',       '0032')

select DefultDim, B_MainSector, C_SecondSector, D_ThirdSection, E_Vendor
from
(
  select DefultDim, DisplayValue, Name
  from #Temp
) d
pivot
(
  max(DisplayValue)
  for Name in (B_MainSector,   C_SecondSector, D_ThirdSection, E_Vendor)
) piv;

您可以找到实时演示Live Demo Here

答案 1 :(得分:0)

重命名值没有任何问题

SELECT DefaultDim
    ,Name
    ,[4] AS B_itsMe
    ,[401] AS i_MadeIt
    ,[32] AS O_K
    ,[40100] AS Fix_This
FROM(
SELECT * FROM temp.dbo.DefaultDimensionView
PIVOT(
        MAX(DisplayValue)
        FOR DisplayValue
        IN ([4], [401], [32], [40100])
        ) AS Piv_DisplayValue
) AS R

样本数据

enter image description here