I seems an simple task but I need some help from the sql experts with this one.
The number of contacts can vary from 1 to 30 persons and I want all the phone numbers in one row per cust_ref.
How can I do this??
I seems an simple task but I need some help from the sql experts with this one.
The number of contacts can vary from 1 to 30 persons and I want all the phone numbers in one row per cust_ref.
How can I do this??
This is a solution without dynamic sql, please try out:
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
by using CROSS APPLY,CTE and UNION ALL we can get the above requirement
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