T:SQL: select values from rows as columns

后端 未结 2 1733
我在风中等你
我在风中等你 2020-12-16 04:15

I have a table for Profiles stores profile properties values in row style, ex:

[ProfileID]     [PropertyDefinitionID]      [PropertyValue]
1               6          


        
2条回答
  •  盖世英雄少女心
    2020-12-16 04:26

    It's easy to do this without PIVOT keyword, just by grouping

    select
        P.ProfileID,
        min(case when PD.PropertyName = 'FirstName' then P.PropertyValue else null end) as FirstName,
        min(case when PD.PropertyName = 'LastName' then P.PropertyValue else null end) as LastName,
        min(case when PD.PropertyName = 'Salary' then P.PropertyValue else null end) as Salary
    from Profiles as P
        left outer join PropertyDefinitions as PD on PD.PropertyDefinitionID = P.PropertyDefinitionID
    group by P.ProfileID
    

    you can also do this with PIVOT keyword

    select
        *
    from
    (
        select P.ProfileID, P.PropertyValue, PD.PropertyName
        from Profiles as P
            left outer join PropertyDefinitions as PD on PD.PropertyDefinitionID = P.PropertyDefinitionID
    ) as P
        pivot
        (
            min(P.PropertyValue)
            for P.PropertyName in ([FirstName], [LastName], [Salary])
        ) as PIV
    

    UPDATE: For dynamic number of properties - take a look at Increment value in SQL SELECT statement

提交回复
热议问题