如何根据相关列的值将值从行透视到列

时间:2019-05-06 16:34:42

标签: sql sql-server pivot aggregation

我正在尝试根据3个值透视一组数据,以便每一行代表与每个ID相关的所有个人资料网址,而每一列都与个人资料代码相关

这个问题与我要解决的问题非常相似,但是它不是根据另一个值Pivot values on column based on grouped columns in SQL

对正在旋转的列进行分组

因此,给出了以下示例表:

Id        ProfileCode  ProfileURL  
-------------------------------------------------------
7ADC7368  IA           http://www.domainIA.com/profile1
5C627D6F  IA           http://www.domainIA.com/profile2
5C627D6F  AG           http://www.domainAG.com/profile1
5C627D6F  AF           http://www.domainAF.com/profile1
664B4AE9  IA           http://www.domainIA.com/profile3
664B4AE9  AF           http://www.domainAF.com/profile2

我希望将其转换为下表:

Id        IA                                AG                                AF
-------------------------------------------------------------------------------------------------------------
7ADC7368  http://www.domainIA.com/profile1  null                              null
5C627D6F  http://www.domainIA.com/profile2  http://www.domainAG.com/profile1  http://www.domainAF.com/profile1
664B4AE9  http://www.domainIA.com/profile3  null                              http://www.domainAF.com/profile2

这是我一直在尝试的代码,但是我找不到将枢轴与配置文件URL及其关联的配置文件代码之间的关联相关联的方法。

declare @tmp TABLE (Id NVARCHAR(15), ProfileCode NVARCHAR(2), ProfileURL NVARCHAR(50))

insert into @tmp (Id, ProfileCode, ProfileURL)
values  ('7ADC7368', 'IA', 'http://www.domainIA.com/profile1'),
        ('5C627D6F', 'IA', 'http://www.domainIA.com/profile2'),
        ('5C627D6F', 'AG', 'http://www.domainAG.com/profile1'),
        ('5C627D6F', 'AF', 'http://www.domainAF.com/profile1'),
        ('664B4AE9', 'IA', 'http://www.domainIA.com/profile3'),
        ('664B4AE9', 'AF', 'http://www.domainAF.com/profile2')

select 
     pvt.id,
    CASE
        WHEN ProfileCode = 'IA' THEN ProfileURL 
    END AS 'IA',
    CASE
        WHEN ProfileCode = 'AF' THEN ProfileURL 
    END AS 'AF',
    CASE
        WHEN ProfileCode = 'AG' THEN ProfileURL
    END AS 'AG'
from (  
    select 
         Id, ProfileCode, ProfileURL
        ,ROW_NUMBER() over(partition by ProfileCode order by ProfileURL) as RowNum
from 
    @tmp
) a
pivot (MAX(ProfileCode) for RowNum in ('IA', 'AF', 'AG') as pvt

如果能为我提供帮助或帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

只需使用条件聚合:

SELECT id,
       MAX(CASE WHEN ProfileCode = 'IA' THEN ProfileURL END) AS IA,
       MAX(CASE WHEN ProfileCode = 'AF' THEN ProfileURL END) AS AF,
       MAX(CASE WHEN ProfileCode = 'AG' THEN ProfileURL END) AS AG
FROM @tmp t
GROUP BY id;

对于给定ID ,如果您有多个相同的代码,则只需要ROW_NUMBER(),并且您希望将结果放在单独的行中。您的样本数据和当前逻辑表明情况并非如此。