T:SQL:从行中选择值作为列

Ala*_*laa 8 sql t-sql sql-server pivot

我在行样式中有一个Profiles store配置文件属性值的表,例如:

[ProfileID]     [PropertyDefinitionID]      [PropertyValue]
1               6                           Jone
1               7                           Smith
1               8                           Mr
1               3                           50000
Run Code Online (Sandbox Code Playgroud)

和另一个属性定义表:

[PropertyDefinitionID]  [PropertyName]
6                       FirstName
7                       LastName
8                       Prefix
3                       Salary
Run Code Online (Sandbox Code Playgroud)

如何使用PIVOT或以任何其他方式以这种方式显示它:

[ProfileID] [FirstName] [LastName]  [Salary]
1           Jone        Smith       5000
Run Code Online (Sandbox Code Playgroud)

Rom*_*kar 12

没有PIVOT关键字,只需按分组即可轻松完成此操作

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
Run Code Online (Sandbox Code Playgroud)

你也可以用PIVOT关键字来做到这一点

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
Run Code Online (Sandbox Code Playgroud)

更新:对于动态数量的属性 - 请查看SQL SELECT语句中的Increment值


Tar*_*ryn 5

看起来你可能有一个未知数量的PropertyName's你需要变成列.如果是这种情况,那么您可以使用动态SQL生成结果:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(PropertyName) 
                    from propertydefinitions
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT profileid, ' + @cols + ' from 
             (
                select p.profileid,
                  p.propertyvalue,
                  d.propertyname
                from profiles p
                left join propertydefinitions d
                  on p.PropertyDefinitionID = d.PropertyDefinitionID
            ) x
            pivot 
            (
                max(propertyvalue)
                for propertyname in (' + @cols + ')
            ) p '

execute(@query)
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.