2016-07-26 92 views
1

我有一个表我使用PIVOT,它的工作原理和正确返回数据透视列的数据,但我有我想要的行中的其他列绑定到枢轴柱。SQL在一列选择PIVOT,但选择其他列连接到枢轴字段

例子:

ID, PhoneType (column to PIVOT), PhoneNumber (value to be pivoted), PhoneAttribute1, PhoneAttribute2, PhoneAttribute3. 

1, Cell, 123456789, call, dontcall, pleasecall 
1, work, 123456780, call2, dontcall2, pleasecall2 
2, Home, 123456782, call2, dontcall2, pleasecall2 

当我透视数据(无属性列),我得到的输出:

ID, CELL, Work, Home 
1, 123456789, 123456780, NULL 
2, NULL, NULL, 123456782 

哪个是正确的,但我想其他attributcolumns添加到该列表使其将每个属性与每个电话号码绑定,如下所示:

ID, CELL, Work, Home, CELLPhoneAttribute1, CELLPhoneAttribute2, CELLPhoneAttribute3, WorkPhoneAttribute1, WorkPhoneAttribute2, WorkPhoneAttribute3,...... 

这可能吗?

我可以用连接来做,但这可能很麻烦,如果我添加更多的phonetypes,它会变得更大。

有什么建议吗?

回答

0

据我所知,这是不可能的,没有使用几个常规的连接。

生成的数据表的预期用途是什么?大多数报告工具可让您轻松进行此分组。例如,在表格矩阵中将SSRS内的行级别和列级别组合在一起。

+0

我需要使用数据作为过程的一部分来运行过滤器和其他操作。所以一个基本的报告不会为这些目的而工作 – Brad

+0

我认为,如果您可以告诉我们更多关于该过程的信息,可以找到更好的解决方案。一般来说,试图在SQL中做你正在做的事情很少是最好的方法,通常可以不做,通过改变你的方法来完成整个任务。 – iamdave

1

您也可以使用条件聚合。在这种情况下,不需要连接。不是最漂亮的,但也不难扩展。

select id, 
     max(case when phone_type = 'Cell' then PhoneNumber end) as CELL, 
     max(case when phone_type = 'work' then PhoneNumber end) as Work, 
     max(case when phone_type = 'Home' then PhoneNumber end) as Home, 
     max(case when phone_type = 'Cell' then PhoneAttribute1 end) as CELLPhoneAttribute1, 
     max(case when phone_type = 'Cell' then PhoneAttribute2 end) as CELLPhoneAttribute2, 
     max(case when phone_type = 'Cell' then PhoneAttribute3 end) as CELLPhoneAttribute3, 
     max(case when phone_type = 'work' then PhoneAttribute1 end) as WorkPhoneAttribute1, 
     max(case when phone_type = 'work' then PhoneAttribute2 end) as WorkPhoneAttribute2, 
     max(case when phone_type = 'work' then PhoneAttribute3 end) as WorkPhoneAttribute3, 
     max(case when phone_type = 'Home' then PhoneAttribute1 end) as HomePhoneAttribute1, 
     max(case when phone_type = 'Home' then PhoneAttribute2 end) as HomePhoneAttribute2, 
     max(case when phone_type = 'Home' then PhoneAttribute3 end) as HomePhoneAttribute3 
    from tbl 
group by id