SQL Pivot具有多个值

时间:2017-01-20 17:02:47

标签: sql sql-server pivot

你好,我有一个像这样的表:

Building    Categories      Properties
-----------------------------------------
Building250 Structure       Steel
Building250 Security        Access Card
Building250 Security        Security Guard
Building250 Security        Fire Alarm System 
Building250 Security        Sprinklered
Building250 Security        Smoke or heat detectors
Building46  Structure       Brick
Building46  Structure       Steel
Building46  Walls           Steel Stud
Building46  Walls           Masonry
Building46  Washroom        OwnSpace
Building46  Washroom        Common
Building46  Security        Access Card
Building46  Security        Burglar Alarm

我需要像这样转动它:

Building    Structure   Security           Walls       Washroom
----------------------------------------------------------------------------
Building250 Steel       Access Card     
                        Security Guard      
                        Fire Alarm System       
                        Sprinklered     
                        heat detectors      
Building46  Brick       Access Card       Steel Stud    OwnSpace
            Steel       Burglar Alarm     Masonry       Common 
                        Sprinklered     

我尝试过SQL Pivot,但由于它需要聚合,因此它只返回给定类别的1个属性。还有另一种方式吗?

这是我的Pivot SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Category) 
                  FROM Buildings
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Building, ' + @cols + ' from 
             (
                SELECT Building, Category, Property, from Buildings
            ) x
            pivot 
            (
                min(Property)
                for Category in (' + @cols + ')
            ) p '

execute(@query)

1 个答案:

答案 0 :(得分:0)

正如您所指出的,Pivot可以进行聚合,虽然有可能的解决方法,但您可以通过以下方式完成所需而无需使用数据透视表。您也可以使用与制作动态数据透视图相同的方法使其动态化。

Select B.Building, Str.Properties Structure, 
       Sec.Properties Security, Walls.Properties Walls, Wash.Properties Washroom
    From (Select Distinct Building From Table) B
    Left Join Table Str On Str.Building = B.Building And Categories = 'Structure'
    Left Join Table Sec On Sec.Building = B.Building And Categories = 'Security'
    Left Join Table Walls On Walls.Building = B.Building And Categories = 'Walls'
    Left Join Table Wash On Wash.Building = B.Building And Categories = 'Washroom'