DECLARE @TABLE TABLE
(
CustNO VARCHAR (50),
RelationNo VARCHAR (50),
POSTCODE VARCHAR (50),
PHONE001 VARCHAR (50),
PHONE002 VARCHAR (50),
PHONE003 VARCHAR (50)
)
INSERT @TABLE
SELECT 'A0002023','N195UN','121408', '02075614860','','' UNION ALL
SELECT 'A0002023','N195UN','121408', '0207561860','','' UNION ALL
SELECT 'E3085141','15252','408121', '5566456', '', '' UNION ALL
SELECT 'E3085141','15252','408121', '256756616', '', '' UNION ALL
SELECT 'ZBT5489','88888','555555', '6665589', '', '' UNION ALL
SELECT 'JEZTSUR1','9999','558121', '9986141', '', '' UNION ALL
SELECT 'JEZTSUR1','9999','558121', '963283', '', '' UNION ALL
SELECT 'JEZTSUR1','9999','558121', '679971', '', ''
当CustNo,RelationNo和PhoneNumber匹配时,尝试合并
的电话号码第二行合并到第一行的第二或第三个电话号码。
输出
CustNO | Relationnumber|phone001| phone002|phone003
A0002023| N195UN| 121408| 02075614860|0207561860|''
E3085141| 15252| 408121| 5566456|256756616|''
ZBT5489 | 88888| 555555| 6665589|''|''
JEZTSUR1| 9999| 558121| 9986141|963283| 679971
答案 0 :(得分:0)
检查这个。
SELECT distinct
m.CustNO
, m.RelationNo
, m.POSTCODE
, PHONE001 = STUFF((
SELECT ',' + md.PHONE001
FROM dbo.@TABLE md
WHERE m.CustNO = md.CustNO and m.RelationNo = md.RelationNo and m.POSTCODE = md.POSTCODE
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.@TABLE m
OutPut: