SQL Server行到Cols

时间:2015-07-14 07:47:11

标签: sql sql-server pivot

我似乎是一个简单的任务,但我需要一些sql专家的帮助。

Table samples and requested result

联系人数量可以从1到30人不等,我想要每个cust_ref一行中的所有电话号码。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

这是一个没有动态sql的解决方案,请试试:

declare @contacts table(cust_ref int,phone varchar(100));
insert into @contacts values(10000,'ph10000a'),(10000,'ph10000b'),(10000,'ph10000c')
                           ,(10001,'ph10001a'),(10001,'ph10001b'),(10001,'ph10001c') 
                           ,(10002,'ph10002a'),(10002,'ph10002b');

SELECT p.*
FROM
( 
    SELECT 'phone'+REPLACE(STR(ROW_NUMBER() OVER(PARTITION BY cust_ref ORDER BY phone),2),' ','0') AS inx,*
    FROM @contacts    
) AS tbl
PIVOT
(
    MIN(phone) FOR inx IN(phone01,phone02,phone03,phone04) --type more...
) AS p        

答案 1 :(得分:0)

通过使用CROSS APPLY,CTE和UNION ALL我们可以得到上述要求

declare @tableA table (RefId int,Phone varchar(10))
insert into @tableA (RefId,Phone)values (10000,'030123456'),(100123,060123445)

Declare @tableB table (CustID  INT,RefId INT,Phone varchar(10)))
insert into @tableB (CustID,RefId,Phone)values 
(1,10000,'030245789'),
(2,10000,'030245889'),
(1,100123,'060245789'),
(2,100123,'060243389'),
(3,100123,'060289389')

; with CTE AS (
select A.RefId,A.Phone As Phone from @tableA A 
UNION 
select B.RefId,B.Phone As Phone from @tableB B )

 select * from (
 Select RefId,
 val,
 COL + CAST(ROW_NUMBER()OVER(PARTITION BY RefId ORDER BY RefId) AS VARCHAR(1))RN  
    FROM CTE 
CROSS APPLY (VALUES ('Phone',Phone))CS(Col,val))T
PIVOT (MAX(VAL) FOR RN IN ([Phone1],[Phone2],[Phone3],[Phone4]))P