T:SQL:从行中选择值作为列
发布时间:2021-01-14 14:50:52  所属栏目:MsSql教程  来源:网络整理 
            导读:我在行样式中有一个Profiles store配置文件属性值的表,例如: [ProfileID] [PropertyDefinitionID] [PropertyValue]1 6 Jone1 7 Smith1 8 Mr1 3 50000 和另一个属性定义表: [PropertyDefinitionID] [PropertyName]6 FirstName7 LastName8 Prefix3 Salary 如
                
                
                
            | 我在行样式中有一个Profiles store配置文件属性值的表,例如: [ProfileID] [PropertyDefinitionID] [PropertyValue] 1 6 Jone 1 7 Smith 1 8 Mr 1 3 50000 和另一个属性定义表: [PropertyDefinitionID] [PropertyName] 6 FirstName 7 LastName 8 Prefix 3 Salary 如何使用PIVOT或任何其他方式以这种方式显示它: [ProfileID] [FirstName] [LastName] [Salary] 1 Jone Smith 5000 解决方法没有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您也可以使用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更新:对于动态数量的属性 – 请查看Increment value in SQL SELECT statement (编辑:海洋资讯信息网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 

